初学Node,仿照写php的时候自定义异常类,捕获异常,然后判断异常是否属于自定义的异常。如果是属于自定义异常,则是客户端错误,如果不是自定义异常,则是服务器内部错误,然后记录日志。问题是在php中可以直接捕获异常,然后intanceof就行,可是在Node中,却无法使用代码:自定义异常类BaseException.js:class BaseException extends Error {
constructor({code = 400, msg = "调用出错", errorCode = "10000"}) {
super();
this.code = code;
this.msg = msg;
this.errorCode = errorCode;
}
}export default BaseException;继承至BaseException的子类ParamsException.js:
import BaseException from './BaseException';class ParamsException extends BaseException {
constructor({code = 405, msg = "参数错误", errorCode = 40005}) {
super({});
this.code = code;
this.msg = msg;
this.errorCode = errorCode;
}
}export default ParamsException;
捕获异常并且判断:
try {
throw new ParamsException({});
} catch (err) {
if (err instanceof BaseException) {
res.send('1111');
} else {
res.send({
code: 500,
msg: "服务器内部错误",
errorMsg: 50000
});
}
}使用instanceof始终无法抛出正确的异常,这种情况是否是intanceof用法问题,有解决办法吗?
constructor({code = 400, msg = "调用出错", errorCode = "10000"}) {
super();
this.code = code;
this.msg = msg;
this.errorCode = errorCode;
}
}export default BaseException;继承至BaseException的子类ParamsException.js:
import BaseException from './BaseException';class ParamsException extends BaseException {
constructor({code = 405, msg = "参数错误", errorCode = 40005}) {
super({});
this.code = code;
this.msg = msg;
this.errorCode = errorCode;
}
}export default ParamsException;
捕获异常并且判断:
try {
throw new ParamsException({});
} catch (err) {
if (err instanceof BaseException) {
res.send('1111');
} else {
res.send({
code: 500,
msg: "服务器内部错误",
errorMsg: 50000
});
}
}使用instanceof始终无法抛出正确的异常,这种情况是否是intanceof用法问题,有解决办法吗?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货