nodejs / community-committee

The Node.js Community Committee (aka CommComm)
MIT License
263 stars 70 forks source link

How to set error.name in extended class Error in Node.js? #631

Closed KaizenTamashi closed 4 years ago

KaizenTamashi commented 4 years ago

I'm trying to set the error name err.name = 'ExpressValidatorError';

of an custom Error class class AppError extends Error

that is passed to centralErrorHandler to filter and handle errors by err.name.

I have did a lot of research but still couldn't figure out why err.name in centralErrorHandler console logs as undefined.

When I change return next(err); in auth.controller.js to throw err;, the err.name does console log as 'ExpressValidatorError' but i'm not sure if using throw is correct.

centralErrorHandler.js

module.exports = (err, req, res, next) => {           
        console.log(err.name);
        if(err.name === 'ExpressValidatorError') err = handleExpressValidatorError(err);            
}

auth.controller.js

const {validationResult} = require('express-validator');

exports.signup = (req, res) => {     
    const errors = validationResult(req); 

      if (!errors.isEmpty()) {
        let err = new AppError(`Invalid login credentials.`, 422);
        err.name = 'ExpressValidatorError';            

        return next(err);
      }

    res.status(200).send(req.user);          
}

appError.js

class AppError extends Error {
    constructor(message, statusCode){
        super(message);

        this.statusCode = statusCode;
        this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';        
        this.isOperational = true;        

        Error.captureStackTrace(this, this.constructor);
    }
}

module.exports = AppError;