Handling specific errors in JavaScript (think exceptions)

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

    As noted in the comments below this is Mozilla specific, but you can use 'conditional catch' blocks. e.g.:

    try {
      ...
      throwSpecificError();
      ...
    }
    catch (e if e.sender === "specific") {
      specificHandler(e);
    }
    catch (e if e.sender === "unspecific") {
      unspecificHandler(e);
    }
    catch (e) {
      // don't know what to do
      throw e;
    } 
    

    This gives something more akin to typed exception handling used in Java, at least syntactically.

提交回复
热议问题