Search code examples
typescriptnext.jsmonitoringobservability

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


Solution

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