Errortype can be extended according to documents . You can define SystemErrorwhich extends the type 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);
SystemError.prototype.setCode = function(code){
this.code = code;
return this;
};
SystemError.prototype.setHttpCode = function(httpCode){
this.httpCode = httpCode;
return this;
};
module.exports = SystemError;
Now you can send your own error:
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
}
});
But all this is only useful if there is a central error handling mechanism. For example, in the application expressjs, you may encounter an error related to the middleware at the end:
var express = require('express');
var app = express();
app.get('/cars', require('./getCars'));
app.put('/cars', require('./putCars'));
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'
});
}
});