Handling specific errors in JavaScript (think exce

2019-01-21 10:05发布

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 prototype of the Error object:

Error.prototype.sender = "";


function throwSpecificError()
{
    var e = new Error();

    e.sender = "specific";

    throw e;
}

Catch specific error:

try
{
    throwSpecificError();
}

catch (e)
{
    if (e.sender !== "specific") throw e;

    // handle specific error
}


Have you guys got any alternatives?

3条回答
放荡不羁爱自由
2楼-- · 2019-01-21 10:44

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.

查看更多
做自己的国王
3楼-- · 2019-01-21 10:44

try-catch-finally.js

Example

_try(function () {
    throw 'My error';
})
.catch(Error, function (e) {
    console.log('Caught Error: ' + e);
})
.catch(String, function (e) {
    console.log('Caught String: ' + e);
})
.catch(function (e) {
    console.log('Caught other: ' + e);
})
.finally(function () {
    console.log('Error was caught explicitly');
});
查看更多
仙女界的扛把子
4楼-- · 2019-01-21 10:52

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
  }
}
查看更多
登录 后发表回答