📖 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
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
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
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
Hint
Create an instance of AppService, call performTask(), then print 'Error logged successfully'.
Practice
(1/5)
1. What is the main purpose of logging exceptions in a NestJS application?
easy
A. To increase the app's memory usage
B. To speed up the application runtime
C. To track and fix errors by recording error details
D. To prevent users from accessing the app
Solution
Step 1: Understand the role of exception logging
Logging exceptions records error details like messages and stack traces to help developers find and fix bugs.
Step 2: Identify the correct purpose
Among the options, only tracking and fixing errors matches the purpose of logging exceptions.
Final Answer:
To track and fix errors by recording error details -> Option C
Quick Check:
Logging exceptions = track and fix errors [OK]
Hint: Logging exceptions helps find bugs by saving error info [OK]
Common Mistakes:
Thinking logging improves app speed
Confusing logging with security features
Believing logging increases memory unnecessarily
2. Which of the following is the correct way to log an error with NestJS Logger inside a catch block?
easy
A. Logger.error(error.message, error.stack, 'MyContext')
B. Logger.log(error.message, 'MyContext')
C. Logger.warn(error.stack, 'MyContext')
D. Logger.debug(error.message, error.stack)
Solution
Step 1: Recall Logger.error method signature
Logger.error takes three arguments: message, stack trace, and optional context string.
Step 2: Match the correct syntax
Logger.error(error.message, error.stack, 'MyContext') correctly uses Logger.error with message, stack, and context. Others use wrong methods or missing parameters.
Final Answer:
Logger.error(error.message, error.stack, 'MyContext') -> Option A
A. Arguments to Logger.error are reversed; message should come first
B. Logger.error cannot be used inside catch blocks
C. Missing await keyword before Logger.error
D. Logger.error requires only one argument
Solution
Step 1: Check Logger.error argument order
Logger.error expects (message, stack, context). Here, stack and message are swapped.
Step 2: Confirm correct usage
Swapping arguments causes wrong log output or errors. Correct order is message first, then stack trace.
Final Answer:
Arguments to Logger.error are reversed; message should come first -> Option A
Quick Check:
Logger.error(message, stack, context) order matters [OK]
Hint: Logger.error needs message first, then stack, then context [OK]
Common Mistakes:
Swapping message and stack arguments
Thinking Logger.error is async needing await
Assuming Logger.error takes only one argument
5. You want to log exceptions in a NestJS global exception filter to capture all errors with context 'GlobalFilter'. Which code snippet correctly implements this?
hard
A. catch(exception: any) {
Logger.log(exception.message, 'GlobalFilter');
}
B. catch(exception: any) {
Logger.error(exception.message, exception.stack, 'GlobalFilter');
}
C. catch(exception: any) {
Logger.warn(exception.stack, 'GlobalFilter');
}
D. catch(exception: any) {
Logger.debug(exception.message, exception.stack);
}
Solution
Step 1: Understand global exception filter logging
Global filters catch all exceptions; logging must use Logger.error with message, stack, and context.
Step 2: Evaluate each option
catch(exception: any) {
Logger.error(exception.message, exception.stack, 'GlobalFilter');
} correctly calls Logger.error with message, stack, and 'GlobalFilter' context. Others use wrong log levels or miss stack/context.
Final Answer:
catch(exception: any) {
Logger.error(exception.message, exception.stack, 'GlobalFilter');
} -> Option B
Quick Check:
Global filter logs errors with Logger.error and context [OK]
Hint: Use Logger.error with message, stack, and context in global filters [OK]
Common Mistakes:
Using Logger.log or Logger.warn instead of Logger.error
Omitting stack trace or context
Using Logger.debug which is too low level
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.