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).
Asked
Active
Viewed 1,358 times
0
-
Do you mean error logging for Next JS `/api` serverless functions or the frontend ? – Lakshya Thakur Sep 30 '22 at 19:26
-
@LakshyaThakur I mean for /api , APIs developed in NextJS – Swanand Keskar Oct 11 '22 at 16:12
2 Answers
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