How can I spot a user error

I need to assign the code / id to my custom error:

This is when I create an error:

var err=new Error('Numero massimo di cambi di username raggiunto');

Anyone who can help me figure out how I can do this?

+1
source share
2 answers

Identify

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);
}
+1
source

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); // 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 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'));

  // 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'
       });
     }
  });
0

Source: https://habr.com/ru/post/1649471/


All Articles