javascript - Node.js custom error handling -
I am working on an application. In that application I am defining some custom error below
'strict experiment'; /** * Validation Error. * The default HTTP status code for validation is 400 (HTTP Bad Request) * * / / * Globals * / var HTTP_BAD_REQUEST = 400; Var NAME = 'Validation Error'; / ** * Constructor * * @ Ultimate {string} Message Verification Error Message * / Function Validation Error (Message) {this.name = NAME; This.message = Message; This.code = HTTP_BAD_REQUEST; } Validation error. Prototype = new error (); / ** * module export * / module.exports = validation error; I now need to import this module to other modules such as
var UnauthorizedError = require ('../ errors / UnauthorizedError') In the controller
// Show some arguments if (some condition) {// call global error handler next (new verification error ('id required The next middleware is the next ();} If any system is false the next () error handler is calling the middleware .
I I have defined my error handler middleware as below
var winston = require ('winston'); var HTTP_INTERNAL_SERVER_ERROR = 500; var MESSAGE = 'internal server error'; / ** * Express Standard Error Middleware * @ Ultimate {Error} Error Object Error * @ PRAM {Object} Request Request Object * @ PRAM {Object} RAS Express Response Object * @ PRAM {Function} Next Next Express Forward * / var middleware = function (err) , Req, res) {winston.error (err); Res.sta Tus (err.code+ HTTP_INTERNAL_SERVER_ERROR) .json (err.message || MESSAGE); }; / ** * module export * / module.exports = function () {return middleware; }; I use my app like ErrorHandler
app.use (errorHandler ()); In the notification error handler, I am sending json data to the customer with some status codes and error messages. But if I check in the postman, the response header
connection → save-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 Content body stack is error To verify, I have verified that the error is not called next and some rules are wrong and the error handler middleware is also not called.
I do not want to answer my question. But for the sake of the community I am posting it. I hope this will be useful for anyone.
Middleware Announcement
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.
Comments
Post a Comment