Swanand Keskar
Swanand Keskar

Reputation: 1073

How to do global error handling for NextJS api?

For getting the stack trace of the error and push it to external system such as NewRelic etc. is there a way to configure Global error handler which wraps all the APIs So that making changes to all the APIs (multiple files is not required, DRY principle).

Upvotes: 0

Views: 2831

Answers (2)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

You can create a resusable withErrorHandler high order function to wrap your /api handlers like so :-

import logger from 'some-logger';

const withErrorHandler = (handler) => async (req, res) => {
  try {
    return handler(req, res);
  } catch (error) {
    // logger comes here
    // your return statement based on error
  }
};

Suppose your handler looks like :-

const handler = (req,res) => {
// doing something
}

You can export it like so :-

export default withErrorHandler(handler)

Upvotes: 1

Yilmaz
Yilmaz

Reputation: 49321

class ErrorHandler extends Error {
  constructor(message, statusCode) {
    // super calls the constructor of the parent class
    super(message);
    this.statusCode = statusCode;
    //  captureStackTrace returns a string that reperesents the location of that particular error in the call. gives us a stack that helps us to find the location of that error in the code. this will help us to find the exact error in our code.
    // "this" is object itself, "this.constructor" constructor of this class
    Error.captureStackTrace(this, this.constructor);
  }
}

export default ErrorHandler;

then in api routes

if (!user) {
    return next(new ErrorHandler("User not found with this ID.", 400));
  }

Upvotes: 1

Related Questions