Errors are an inevitable part of any web application. Sometime, they may be caused by users requesting non-existent resources, submitting invalid input, attempting to upload malicious content, or they may be caused by internal server errors.
It is very important that these errors are handled accordingly, or they can lead to poor user experience, security vulnerability, or even application crush.
In this lesson, how handles errors when they arise in different parts of a Next.js application, and how you can manage them effectively to ensure a smooth user experience.
Error handling in API routes
Let's start with the API routes.
First of all, make sure your logic, let it be pulling or posting data to a database, requesting data from a remove API, or performing eny other tasks, is always wrapped inside a try
/catch
block. This helps you catch the runtime errors, and preventing them from crushing your application.
1export default async function GET(req, res) {
2 try {
3 // Simulate a task
4 const result = await someTask();
5
6 // Returns a 200 response if task is successful
7 res
8 .status(200)
9 .json({ success: true, message: "Task successful.", result: result });
10 } catch (error) {
11 // Returns a 500 response if task is unsuccessful
12 res
13 .status(500)
14 .json({ success: false, message: "Task failed.", error: error });
15 }
16}
When the error occurs, you need to make sure a proper response is returned, with the right response code and structured response body.
In the above example, the response code is 500
, which indicates there are something wrong on the server. It is a generic error code and doesn't add much information.
Optionally, you can use the more specific response codes such as: