Express: How to set error.name in extended class Error in Node.js?

Created on 11 Jul 2020  路  4Comments  路  Source: expressjs/express

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;
question

Most helpful comment

In your signup controller you're calling return next(err);, however, you haven't included next as a param for the handler.
When I run your code, the error I get is ReferenceError: "next is not defined". And updating the handler signature to exports.signup = (req, res, next) => { ... logs as you expect in centralErrorHandler.

All 4 comments

In your signup controller you're calling return next(err);, however, you haven't included next as a param for the handler.
When I run your code, the error I get is ReferenceError: "next is not defined". And updating the handler signature to exports.signup = (req, res, next) => { ... logs as you expect in centralErrorHandler.

@mastermatt Thank you, the missing next parameter is causing the issue.
For some reason i didn't encounter the ReferenceError: "next is not defined" in the console log.

Glad to help.

I first changed your logging to log the whole error object instead of just err.name, that gave me the ReferenceError and it all fell into place from there.

@mastermatt Thank you :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

afanasy picture afanasy  路  3Comments

prashantLio picture prashantLio  路  3Comments

ER-GAIBI picture ER-GAIBI  路  3Comments

nove1398 picture nove1398  路  3Comments

despairblue picture despairblue  路  3Comments