Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Created November 18, 2016 15:17
Show Gist options
  • Save karlpokus/ae14991521233b6e70cf77f8b27978de to your computer and use it in GitHub Desktop.
Save karlpokus/ae14991521233b6e70cf77f8b27978de to your computer and use it in GitHub Desktop.
Proper error handling in node express

Proper error handling in node express

server

  • Place errorHandler after all routes and before .listen
  • Forget process.env.NODE_ENV
  • Use knas when raising errors if you need to produce http status codes
function errorHandler(err, req, res, next) {
  // err is either obj or string
  res.status(err.status || 500).send(err.message || err); 
};

// routes here..

app.use(errorHandler);

// .listen

client

ajax

$.ajax({
  error: function(a, b, c) {
    // a.responseText is the actual error string (!) passed from the server like err.message
    // a.statusText is the http status code
    // b is a string about timeouts and parser errors
    // c is the same as a.statusText
    next(a.responseText || a.statusText);
  }
});

Ajax handlers vs http status codes

  • 2XX will run successHandler
  • 3xx - 5xx will run errorHandler

Relevant http status codes

  • 400 bad request (from client)
  • 401 unauthorized
  • 404 not found
  • 500 internal server error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment