Handling specific errors in JavaScript (think exceptions)

前端 未结 6 1754
醉梦人生
醉梦人生 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:32

    I didn't love any of these solutions so I made my own. The try-catch-finally.js is pretty cool except that if you forget one little underscore (_) before the try then the code will still run just fine, but nothing will get caught ever! Yuck.

    CatchFilter

    I added a CatchFilter in my code:

    "use strict";
    
    /**
     * This catches a specific error. If the error doesn't match the errorType class passed in, it is rethrown for a
     * different catch handler to handle.
     * @param errorType The class that should be caught
     * @param funcToCall The function to call if an error is thrown of this type
     * @return {Function} A function that can be given directly to the `.catch()` part of a promise.
     */
    module.exports.catchOnly = function(errorType, funcToCall) {
      return (error) => {
        if(error instanceof errorType) {
          return funcToCall(error);
        } else {
          // Oops, it's not for us.
          throw error;
        }
      };
    };
    

    Now I can filter

    Now I can filter like in C# or Java:

    new Promise((resolve, reject => {
       
    }).catch(CatchFilter.catchOnly(MyError, err =>
       console.log("This is for my error");
    }).catch(err => {
       console.log("This is for all of the other errors.");
    });
    

提交回复
热议问题