How can you bubble errors so that they can be caught in a single try / catch block?

I have an object with functions that cause errors,

myObj = {
  ini:function(){
    this.f();
  },
  f:function(){
   throw new Error();
  } 
};

but I only want to catch exceptions when the object is created

try{
  var o = new myObj();
}catch(err){
  alert("error!");
}

it looks like I should have try / catch blocks everywhere = / to catch an error event in different areas of functions

try{
    myObj = {
      ini:function(){
        try{
          this.f();
        }catch(err){
         alert("f threw an err");
        }
      },
      f:function(){
       throw new Error();
      } 
    };
}catch(err){
 alert("error happend while crating Obj");
}

But I only want to capture from one place = / How to do it?

+5
source share
3 answers

Let your function generate an object of a certain type, and then in your catch block check if (err instanceof MyExceptionObj)and process it accordingly, otherwise regenerate it.

By rethrow, I mean:

, , , . , JS.

try {
   if ($.browser.msie) {
      throw new UnsupportedBrowserException();
   }
} catch (ex) {
   if (ex instanceof UnsupportedBrowserException) {
      alert('Your browser isn't supported.');
   } else {
      // We don't know how to handle this exception, throw it back.
      throw ex;
   }
}

.

+8

JavaScript 1.7 . :

try {
  0();
} catch (ex if ex instanceof TypeError) {
  // only catch TypeErrors
}

, instanceof, , true.

+4

perhaps instead of throwing an error and then catching it, you can simply call the function.

0
source

Source: https://habr.com/ru/post/1736186/


All Articles