what are generic way to handle error in node js

what are generic way to handle error in nodejs?

If you want to implement good app your applications must have informative error messages to notify clients exactly why their request has failed. Errors might be caused either by the client (e.g., wrong input data) or by the server (e.g., a bug in the code). what are resolution’s of error. for a best practice API error response must have following things

  • Error Code
  •  Message
  • Description
  • Resolution

For example:

“error”: {

       “code”: 10001,

       “message”: “Invalid Email”,

       “description”: “please enter valid email id.”,

       “resolution”: “your email must have @.com/.in or domain name”

   }

Error Handling

Because of the asynchronous nature of Node.js and callback patterns, it’s not a trivial task to catch and log for future analysis the state in which errors happen. In the Chapter 17 of Pro Express.js, we cover the use of domains with Express.js apps. The use of domains for error handling in Express.js is a more advanced technique and, for most implementations right out of the box, framework’s built-in error handling might prove sufficient (along with custom error handling middleware).

The error handler spits out the error status (500, Internal Server Error), stack trace, and error message. It is enabled by this code only when the app is in development mode:

if (app.get(‘env’) === ‘development’) {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error’, {
message: err.message,
error: err
});
});
}

 

Tip: app.get(‘env’) is a convenient method for process.env.NODE_ENV; in other words, the preceding line can be rewritten with process.env.NODE_ENV === ‘development’

This makes sense because error handling is typically used across the whole application. Therefore, it’s best to implement it as middleware.

For custom error-handler implementations, the middleware is the same as any other except that it has one more parameter, error

// Main middleware
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send();
});

We can use res.status(500).end() to achieve a similar result, because we’re not sending any data (e.g., an error message). It’s recommended to send at least a brief error message, because it will help the debugging process when problems occur. In fact, the response can be anything: JSON, text, a redirect to a static page, or something else.

app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send({status:500, message: ‘internal error’, type:’internal’});
})

Note: as good practice Always using proper HTTP response statuses such as
401, 400, 500, and so on, is recommended. Refer to List 9–1 for a quick reference.

Main HTTP Status Codes

  • 200- OK; Standard response for successful HTTP requests
  • 201- Created; Request has been fulfilled. New resource created
  • 204- No Content; Request processed. No content returned
  • 301- Moved Permanently; This and all future requests directed to the given URI
  • 304- Not Modified; Resource has not been modified since last requested
  • 400- Bad Request; Request cannot be fulfilled due to bad syntax
  • 401- Unauthorized; Authentication is possible, but has failed
  • 403- Forbidden; Server refuses to respond to request
  • 404- Not Found; Requested resource could not be found
  • 500- Internal Server Error; Generic error message when server fails
  • 501- Not Implemented; Server does not recognize method or lacks ability to fulfill
  • 503- Service Unavailable; Server is currently unavailable