0

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).

Swanand Keskar
  • 1,023
  • 1
  • 13
  • 27

2 Answers2

1
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));
  }
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • this would requires changes at multiple places , what I am more interested towards is DRY(Do not repeat yourself) principle in NextJS framework as mentioned in question. – Swanand Keskar Oct 11 '22 at 16:13
1

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)
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39