您将如何实现不同类型的错误,以便能够捕获特定的错误并让其他错误浮现出来?
实现这一点的一种方法是修改Error
对象的原型:
Error.prototype.sender = "";
function throwSpecificError()
{
var e = new Error();
e.sender = "specific";
throw e;
}
捕获特定错误:
try
{
throwSpecificError();
}
catch (e)
{
if (e.sender !== "specific") throw e;
// handle specific error
}
你们还有别的选择吗?
发布于 2009-09-16 15:09:17
要创建自定义异常,可以从Error
对象继承:
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
}
}
在不继承Error
的情况下,最简单的方法可能是抛出一个具有名称和消息属性的简单对象:
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
}
}
发布于 2009-09-16 15:08:22
正如在下面的注释中所指出的,这是特定于Mozilla的,但您可以使用“conditional catch”块。例如:
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;
}
这提供了更类似于Java中使用的类型化异常处理的东西,至少在语法上是这样。
发布于 2019-11-28 06:21:38
用于导出使用的模块
/**
* Custom InputError
*/
class InputError extends Error {
/**
* Create InputError
* @param {String} message
*/
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Custom AuthError
*/
class AuthError extends Error {
/**
* Create AuthError
* @param {String} message
*/
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Custom NotFoundError
*/
class NotFoundError extends Error {
/**
* Create NotFoundError
* @param {String} message
*/
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = {
InputError: InputError,
AuthError: AuthError,
NotFoundError: NotFoundError
};
导入到脚本中:
const {InputError, AuthError, NotFoundError} = require(path.join(process.cwd(), 'lib', 'errors'));
使用:
function doTheCheck = () =>
checkInputData().then(() => {
return Promise.resolve();
}).catch(err => {
return Promise.reject(new InputError(err));
});
};
外部调用代码:
doTheCheck.then(() => {
res.send('Ok');
}).catch(err => {
if (err instanceof NotFoundError) {
res.status(404).send('Not found');
} else if (err instanceof AuthError) {
res.status(301).send('Not allowed');
} else if (err instanceof InputError) {
res.status(400).send('Input invalid');
} else {
console.error(err.toString());
res.status(500).send('Server error');
}
});
https://stackoverflow.com/questions/1433558
复制相似问题