Node.js custom error handling

2019-06-03 23:18发布

I am working on an application. In that application I am defining some custom error like below

'use strict';

/**
 * Validation error.
 * The Default HTTP STATUS CODE for ValidationError is 400 (HTTP BAD REQUEST)
 *
 */

/* Globals */
var HTTP_BAD_REQUEST = 400;
var NAME = 'ValidationError';

/**
 * Constructor
 *
 * @param {String}      message       The validation error message
 */
function ValidationError(message) {
  this.name = NAME;
  this.message = message;
  this.code = HTTP_BAD_REQUEST;
}

ValidationError.prototype = new Error();

/**
 * Module exports
 */
module.exports = ValidationError;

Now I use require to import this module in other modules like

var UnauthorizedError = require('../errors/UnauthorizedError')

In controller

// perform some logic
if(somecondition) {
    // call global error handler
    next(new ValidationError('id is must');
} else {
    // call next middleware
    next();
}

Enen if somecondition is false next() is calling error handler middleware.

I defined my error handler middleware like below

var winston = require('winston');
var HTTP_INTERNAL_SERVER_ERROR = 500;
var MESSAGE = 'Internal Server Error';

/**
 * Express standard error middleware
 *
 * @param  {Error}      err     error object
 * @param  {Object}     req     express request object
 * @param  {Object}     res     express response object
 * @param  {Function}   next    express next function
 */
var middleware = function(err, req, res) {
  winston.error(err);
  res.status(err.code || HTTP_INTERNAL_SERVER_ERROR).json(err.message || MESSAGE);
};

/**
 * Module exports
 */
module.exports = function() {
  return middleware;
};

I use errorHandler in my app like

app.use(errorHandler());

NOTICE that in error handler I am sending json data to client with some status code and error message. But if I check in postman the response headers are

Connection → keep-alive
Content-Length → 695
Content-Type → text/html; charset=utf-8
Date → Thu, 22 Jan 2015 14:18:13 GMT
X-Content-Type-Options → nosniff
X-Powered-By → Express

The content body is stack trace of error I have verified that next with error is not called and somecondition is false and error Handler middleware is also not called.

1条回答
该账号已被封号
2楼-- · 2019-06-03 23:30

I don't want to answer my own question. But for the sake of community I am posting it. I hope it will be useful to anyone.

The below middleware declaration

var middleware = function(err, req, res) {
  winston.error(err);
  res.status(err.code || HTTP_INTERNAL_SERVER_ERROR).json(err.message || MESSAGE);
};

Error middleware should accept 4 arguments.

查看更多
登录 后发表回答