Blog>
Snippets

Custom Error Handling for Next.js API Routes

Display a custom method for handling errors in API routes using a combination of try/catch blocks and a centralized error handling function.
class ApiError extends Error { constructor(status, message) { super(message); this.status = status; } }

// Use this to throw API specific errors
// throw new ApiError(404, 'Not found');
Defines a custom ApiError class extending the native Error class that includes a status code along with the error message for API error handling.
const errorHandler = (err, req, res, next) => { if (err instanceof ApiError) { res.status(err.status).json({ error: err.message }); } else { res.status(500).json({ error: 'Internal Server Error' }); } };
Defines a centralized error handler that checks if the error is an instance of ApiError and sends a response with the respective status code and error message; otherwise, sends a generic 500 Internal Server Error.
export default async function handler(req, res) { try { // Your API route logic } catch (error) { // If an error occurs, pass it to the centralized error handler errorHandler(error, req, res); } }
This is an example of a Next.js API route that uses try/catch to handle errors. If an error occurs during the API route logic, it is passed to the centralized error handler.