Returning 404 for Missing To-Do Items
Introduction
Welcome to this lesson on handling missing Todo items in your NestJS REST API by returning a 404 error. So far, you've learned how to set up basic GET, POST, PUT, and DELETE requests for a Todo application. You've also enhanced your API with filters and specific modifiers. In this lesson, we'll focus on improving user experience by correctly handling "not found" errors, specifically the "404 Not Found" error for missing Todo items. Adding robust error handling ensures that your API is both user-friendly and reliable.
Understanding REST Controllers in NestJS
First, let's briefly review what a controller is in NestJS. A controller is a class that handles incoming HTTP requests and returns responses to the client. In the previous lessons, you've already created a TodoController to manage various CRUD operations. Just as a quick reminder, here's how we set up the handlers in the controller:
In this example, the findOne method takes an ID as a parameter and looks up a To-Do item with that ID. If the item exists, it is returned as a TodoDto.
Error Handling in NestJS
Handling errors properly is crucial for creating a robust API. In HTTP status codes, a "404 Not Found" error indicates that the requested resource could not be found. NestJS makes error handling straightforward by using built-in exceptions.
Common HTTP Status Codes
Before we dive into the specifics, let's quickly go over some common HTTP status codes you might encounter:
- 200 OK: The request succeeded.
- 201 Created: A new resource was created.
- 400 Bad Request: The request was invalid or cannot be served.
- 404 Not Found: The requested resource could not be found.
- 500 Internal Server Error: The server encountered an unexpected condition.
How to Handle Errors in NestJS
