How can I identify custom error

前端 未结 2 1966
一整个雨季
一整个雨季 2020-12-22 03:30

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\'         


        
相关标签:
2条回答
  • 2020-12-22 03:57

    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);
    }
    
    0 讨论(0)
  • 2020-12-22 04:11

    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'
           });
         }
      });
    
    0 讨论(0)
提交回复
热议问题