0
0
NestJSframework~30 mins

Logging exceptions in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Logging Exceptions in NestJS
📖 Scenario: You are building a simple NestJS application that needs to handle errors gracefully. When an error happens, you want to log the error message so you can understand what went wrong later.
🎯 Goal: Learn how to catch exceptions in a NestJS service and log the error messages using NestJS's built-in Logger.
📋 What You'll Learn
Create a service method that throws an error
Add a Logger instance to the service
Catch the error inside the method and log the error message
Print a message indicating the error was logged
💡 Why This Matters
🌍 Real World
Logging errors helps developers find and fix problems quickly in real applications.
💼 Career
Knowing how to log exceptions is essential for backend developers and DevOps engineers to maintain reliable services.
Progress0 / 4 steps
1
Create a service method that throws an error
Create a class called AppService with a method performTask that throws an error with the message 'Something went wrong!'.
NestJS
Need a hint?

Define a class with a method that uses throw new Error('Something went wrong!').

2
Add a Logger instance to the service
Inside the AppService class, add a private property called logger that is an instance of Logger from @nestjs/common. Initialize it with new Logger(AppService.name).
NestJS
Need a hint?

Import Logger and create a private property logger initialized with new Logger(AppService.name).

3
Catch the error and log the error message
Modify the performTask method to use a try-catch block. Inside try, throw the error as before. Inside catch, use this.logger.error(error.message) to log the error message.
NestJS
Need a hint?

Wrap the error throw in try and catch it to log the message with this.logger.error(error.message).

4
Print a message indicating the error was logged
After calling performTask() on an instance of AppService, print 'Error logged successfully' to the console.
NestJS
Need a hint?

Create an instance of AppService, call performTask(), then print 'Error logged successfully'.