I need to assigne an code/id to my custom error:
This is when I create the error:
var err=new Error(\'Numero massimo di cambi di username raggiunto\'
Define
function MyError(code, message) {
this.code = code;
this.message = message;
Error.captureStackTrace(this, MyError);
}
util.inherits(MyError, Error);
MyError.prototype.name = 'MyError';
Raise
throw new MyError(777, 'Smth wrong');
Catch
if (err instanceof MyError) {
console.log(err.code, err.message);
}
Error
type can be extended as per the docs. You can define an SystemError
that extends Error
type:
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;
Now you can throw your custom 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 of this is only beneficial when you have a central error handling mechanism. For example in an expressjs
app, you can have an error catching middleware at the end:
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'
});
}
});