Lesson 5
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:

TypeScript
1@Controller('todos') 2export class TodoController { 3 constructor(private readonly todoService: TodoService) {} 4 5 @Get() 6 findAll(): TodoDto[] { 7 return this.todoService.findAll(); 8 } 9 10 @Get(':id') 11 findOne(@Param('id') id: string): TodoDto { 12 return this.todoService.findOne(id); 13 } 14 15 // ... other POST, PUT, and DELTE handlers 16}

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

NestJS provides a set of built-in exceptions that you can use to handle errors gracefully. The NotFoundException is particularly useful for our case:

TypeScript
1import { NotFoundException } from '@nestjs/common'; 2 3throw new NotFoundException('Todo not found');

When this exception is thrown, NestJS will automatically send a 404 response to the client.

Implementing the `findOne` Method

Let's start by enhancing the findOne method to return a 404 status code if a To-Do item is not found. Here is the updated method:

Code Example
TypeScript
1@Get(':id') 2findOne(@Param('id') id: string): TodoDto { 3 const todo = this.todoService.findOne(id); 4 5 if (!todo) { 6 throw new NotFoundException('Todo not found'); 7 } 8 9 return todo; 10}
Implementing the `update` Method

Next, let's enhance the update method to handle missing items.

Code Example
TypeScript
1@Put(':id') 2update(@Param('id') id: string, @Body() todo: UpdateTodoDto) { 3 const updatedTodo = this.todoService.update(id, todo); 4 5 if (!updatedTodo) { 6 throw new NotFoundException('Todo not found'); 7 } 8 9 return updatedTodo; 10}
Implementing the `complete` Method

Finally, let's address the complete method, which marks a To-Do item as complete.

Code Example
TypeScript
1@Put(':id/complete') 2complete(@Param('id') id: string): TodoDto { 3 const completedTodo = this.todoService.markComplete(id); 4 5 if (!completedTodo) { 6 throw new NotFoundException('Todo not found'); 7 } 8 9 return completedTodo; 10}
Summary and Conclusion

In this lesson, we focused on enhancing your NestJS REST API to handle missing Todo items by returning a 404 error. We looked at:

  • Understanding the role of controllers in handling HTTP requests.
  • How to handle errors in NestJS using built-in exceptions.
  • Updating the findOne, update, and complete methods to return a 404 status code when the requested item doesn't exist.

By implementing these techniques, your API is now more user-friendly and reliable. Well done on getting to the end of this lesson and this course! You are now equipped with the knowledge to build and handle robust REST APIs using NestJS. Up next are the practice exercises to reinforce what you've learned. Keep exploring and happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.