3

I am fairly new to express and want to know if there exists a global error catcher. I am working on an already existing code with all the controllers created and it would be rookie to implement try and catch in all the controllers. I need a global error catcher to that detects breaks in the code and responds to the client. is there an existing library for that or an existing code implementation.

Oto-Obong Eshiett
  • 527
  • 1
  • 8
  • 17

2 Answers2

7

If your controllers aren't asynchronous, you can simply add error handler after you registered all of your route

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    throw new Error('Something went wrong');
});

// Add more routes here

// Error handler
app.use(function (err, req, res, next) {
    // All errors from non-async route above will be handled here
    res.status(500).send(err.message)
});

app.listen(port);

If your controllers are asynchronous, you need to add a custom middleware to your controller to handle async error. The middleware example is taken from this answer

const express = require('express');
const app = express();
const port = 3000;

// Error handler middleware for async controller
const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

app.get('/', asyncHandler(async (req, res) => {
    throw new Error("Something went wrong!");
}));

// Add more routes here

// Error handler
app.use(function (err, req, res, next) {
    // All errors from async & non-async route above will be handled here
    res.status(500).send(err.message)
})

app.listen(port);
Owl
  • 6,337
  • 3
  • 16
  • 30
0

Here is a version using async/await:

import express from 'express';

const app = express();
const port = 3000;

// Error handler middleware for async controller
function asyncErrorHandler(fn) {
  return async (req, res, next) => {
    try {
      await fn(req, res, next)
    } catch (e) {
      return next(e)
    }
  }
};

app.get('/', asyncErrorHandler(async (req, res) => {
  throw new Error("Something went wrong!");
}));

// Error handler
app.use(function (err, req, res, next) {
  // All errors from async & non-async route above will be handled here
  if (err) {
    // console.log(err)
    return (
      err.message ? res.status(err.statusCode || 500).send(err.message) : res.sendStatus(500)
    )
  }
  next()
})

app.listen(port);
LW001
  • 2,452
  • 6
  • 27
  • 36
Pankaj
  • 37
  • 7