How to create global error handler in next js for API?

clock icon

asked 2 months ago

message

1 Answers

eye

6 Views

I created a function for handling the error but I have to pass this function to every try-catch block of the API. How can I avoid that? Is there a better way to handle API errors in NextJS?

The function which I created, please suggest any doc or example

const errorHandler = (err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  const isDevelopment = process.env.NODE_ENV === 'development';
  // console.log("err",err);
  const responseMessage = isDevelopment ? `invalid request ${err.message}` : 'Something went wrong';
  return res.status(statusCode).json({
    status: false,
    message: responseMessage,
  });
};


module.exports = errorHandler;

1 Answers

If you already use axios, you could use axios.interceptor which intercept all request to API so that you can adjust your function.

https://axios-http.com/docs/interceptors

ex)

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // 401 Unauthorized error handlong
    } else if (error.response && error.response.status === 404) {
      // 404 Not Found error handling
    } else if (error.response && error.response.status === 500) {
      // 500 Internal Server Error handling
    } else {
      // ETC
    }
    return Promise.reject(error);
  }
);

If you don't want to use axios, there's also Next.js built-in feature called 'middleware' which do the similar thing(intercept all request to specific API endpoint you want or to ALL).

https://nextjs.org/docs/app/building-your-application/routing/middleware

Top Questions