我需要为自定义错误分配代码/ ID:
这是我创建错误的时候:
var err=new Error('Numero massimo di cambi di username raggiunto');
有谁帮我理解我怎么做?
答案 0 :(得分:1)
定义
function MyError(code, message) {
this.code = code;
this.message = message;
Error.captureStackTrace(this, MyError);
}
util.inherits(MyError, Error);
MyError.prototype.name = 'MyError';
抬起
throw new MyError(777, 'Smth wrong');
捕捉
if (err instanceof MyError) {
console.log(err.code, err.message);
}
答案 1 :(得分:0)
Error
输入can be extended as per the docs。您可以定义扩展SystemError
类型的Error
:
var util = require('util');
function SystemError(message, cause){
this.stack = Error.call(this,message).stack;
this.message = message;
this.cause = cause;
}
util.inherits(SystemError,Error); // nodejs way of inheritance
SystemError.prototype.setCode = function(code){
this.code = code;
return this;
};
SystemError.prototype.setHttpCode = function(httpCode){
this.httpCode = httpCode;
return this;
};
module.exports = SystemError;
现在您可以抛出自定义错误:
var SystemError = require('./SystemError);
fs.read('some.txt',function(err,data){
if(err){
throw new SystemError('Cannot read file',err).setHttpCode(404).setCode('ENOFILE');
} else {
// do stuff
}
});
但是当你有一个中央错误处理机制时,所有这些都是有益的。例如,在expressjs
应用中,您可能会在最后捕获中间件时出错:
var express = require('express');
var app = express();
app.get('/cars', require('./getCars'));
app.put('/cars', require('./putCars'));
// error handling
app.use( function(err, req, res, next){
if(err instanceof SystemError){
res.status(err.httpCode).send({
code: err.code,
message: err.message
});
} else {
res.status(500).send({
code: 'INTERNAL',
message: 'Internal Server Error'
});
}
});