program story

JavaScript 비동기 콜백에서 발생한 예외를 포착 할 수 있습니까?

inputbox 2020. 12. 4. 08:11
반응형

JavaScript 비동기 콜백에서 발생한 예외를 포착 할 수 있습니까?


JavaScript 콜백에서 예외를 포착하는 방법이 있습니까? 가능할까요?

Uncaught Error: Invalid value for property <address>

다음은 jsfiddle입니다. http://jsfiddle.net/kjy112/yQhhy/

try {
    // this will cause an exception in google.maps.Geocoder().geocode() 
    // since it expects a string.
    var zipcode = 30045; 
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 5,
        center: new google.maps.LatLng(35.137879, -82.836914),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    // exception in callback:
    var geo = new google.maps.Geocoder().geocode({ 'address': zipcode }, 
       function(geoResult, geoStatus) {
          if (geoStatus != google.maps.GeocoderStatus.OK) console.log(geoStatus);
       }
    );
} catch (e) {
    if(e instanceof TypeError)
       alert('TypeError');
    else
       alert(e);
}​

예제에서 아무것도 포착하지 못하는 이유는 geocode()콜백이 호출되면 try/catch블록이 끝났기 때문입니다. 따라서 geocode()콜백은 try블록 의 범위 밖에서 실행 되므로 잡을 수 없습니다.

내가 아는 한, JavaScript 콜백에서 발생하는 예외를 잡는 것은 불가능합니다 (적어도 간단한 방식은 아닙니다).


예, window.onerror 의 기본 동작을 재정의 할 수 있습니다 .

window.onerror = function(message, file, lineNumber) {
  // all errors will be caught here
  // you can use `message` to make sure it's the error you're looking for
  // returning true overrides the default window behaviour
  return true; 
};

실제로 JavaScript 콜백 함수 내에서 발생하는 예외를 포착 할 수 있습니다.

핵심은 try/catch콜백 코드 내 에서 블록 을 설정하는 try/catch것입니다. 콜백 코드 외부의 모든 블록은 콜백 코드가 실행될 때 이미 종료 되었기 때문입니다. 따라서 try/catch블록은 콜백 함수가 호출 될 때 발생하는 예외를 포착 할 수 없지만 다음과 같은 작업을 수행 할 수 있습니다.

// this will cause an exception ing google.maps.Geocoder().geocode() 
// since it expects a string.
var zipcode = 30045; 
var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 5,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
// exception in callback:
var geo = new google.maps.Geocoder().geocode({ 'address': zipcode }, 
   function(geoResult, geoStatus) {
      try {
          if (geoStatus != google.maps.GeocoderStatus.OK) console.log(geoStatus);
      } catch(e){
          alert("Callback Exception caught!");
      }
   }
);

예외가 발생하면이를 캡처 할 수 있습니다. 그게 사실인지 아닌지 100 % 확신하지 못했기 때문에 확인하기 위해 테스트 코드를 작성했습니다. 예외는 Chrome 19.0.1055.1 dev에서 예상대로 캡처됩니다.


원숭이가 콘솔 로그를 패치하여 오류를 감지했습니다.

if(window.console && console.error){
    var old = console.error;
    console.error = function(){
        if(arguments[0].indexOf('Google Maps API error')!=-1){
            alert('Bad Google API Key '+ arguments[0]);
        }
        Array.prototype.unshift.call(arguments);

        old.apply(this, arguments);
    }
}

내 접근 방식은 다음과 같습니다.

// the purpose of this wrapper is to ensure that any
// uncaught exceptions after a setTimeout still get caught
function callbackWrapper(func) {
    return function() {
        try {
            func();
        } catch (err) {
            // callback will reach here :)
            // do appropriate error handling
            console.log("error");
        }
    }
}

try {
    setTimeout(callbackWrapper(function() {throw "ERROR";}), 1000);
} catch (err) {
    // callback will never reach here :(
}

모든 답변에 따르면 try / catch + callback은 다른 컨텍스트에 설정되어 있지만이 코드는 try / catch가 어떻게 작동하는지 설명 할 수 있습니까?

function doSomeAsynchronousOperation(cb) {
  cb(3);
}

function myApiFunc() {
  /*
   * This pattern does NOT work!
   */
  try {
    doSomeAsynchronousOperation((err) => {
      if (err) {
        console.log('got here');
        throw err;
      }

    });
  } catch (ex) {
    console.log(ex);
  }
}

myApiFunc();

참고URL : https://stackoverflow.com/questions/3677783/is-it-possible-to-catch-exceptions-thrown-in-a-javascript-async-callback

반응형