Handling specific errors in JavaScript (think exceptions)

前端 未结 6 1765
醉梦人生
醉梦人生 2020-12-02 11:28

How would you implement different types of errors, so you\'d be able to catch specific ones and let others bubble up..?

One way to achieve this is to modify the

6条回答
  •  醉话见心
    2020-12-02 12:29

    To create custom exceptions, you can inherit from the Error object:

    function SpecificError () {
    
    }
    
    SpecificError.prototype = new Error();
    
    // ...
    try {
      throw new SpecificError;
    } catch (e) {
      if (e instanceof SpecificError) {
       // specific error
      } else {
        throw e; // let others bubble up
      }
    }
    

    A minimalistic approach, without inheriting from Error, could be throwing a simple object having a name and a message properties:

    function throwSpecificError() {
      throw {
        name: 'SpecificError',
        message: 'SpecificError occurred!'
      };
    }
    
    
    // ...
    try {
      throwSpecificError();
    } catch (e) {
      if (e.name == 'SpecificError') {
       // specific error
      } else {
        throw e; // let others bubble up
      }
    }
    

提交回复
热议问题