0
0
NestJSframework~30 mins

Built-in HTTP exceptions in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Built-in HTTP Exceptions in NestJS
📖 Scenario: You are building a simple NestJS API that returns user data. You want to handle cases where a user is not found by using NestJS's built-in HTTP exceptions.
🎯 Goal: Create a NestJS controller that uses the built-in NotFoundException to respond with a 404 error when a user is not found.
📋 What You'll Learn
Create a users array with specific user objects
Add a variable to hold the user ID to search for
Use the NotFoundException from NestJS to throw an error if the user is not found
Complete the controller method to return the found user or throw the exception
💡 Why This Matters
🌍 Real World
Handling errors with proper HTTP status codes is essential in building APIs that clients can understand and react to.
💼 Career
Knowing how to use NestJS built-in exceptions is a common requirement for backend developers working with NestJS to build robust APIs.
Progress0 / 4 steps
1
Create the users data array
Create a constant array called users with these exact objects: { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, and { id: 3, name: 'Charlie' }.
NestJS
Need a hint?

Use const users = [ ... ] with the exact user objects inside.

2
Add a user ID variable to search
Create a constant called userId and set it to the number 4.
NestJS
Need a hint?

Use const userId = 4; exactly.

3
Find the user or throw NotFoundException
Import NotFoundException from @nestjs/common. Then create a constant called user that finds the user in users with id equal to userId. If no user is found, throw new NotFoundException('User not found').
NestJS
Need a hint?

Use users.find(u => u.id === userId) and throw new NotFoundException('User not found') if user is undefined.

4
Complete the controller method to return the user
Create a function called getUser that returns the user constant. Export this function.
NestJS
Need a hint?

Define getUser as a function that returns user and export it.