Learn the essentials of error handling and logging in NestJS applications. Discover how to manage exceptions, implement custom logging, and build robust, scalable backend systems with NestJS. Perfect for developers aiming to master NestJS best practices!
Imagine you’re running a lemonade stand, and suddenly, a customer says their lemonade tastes funny. How would you fix it? First, you’d figure out what went wrong (error handling), and then you’d write it in your notebook to make sure it doesn’t happen again (logging). In the world of coding, NestJS is like the super-organized lemonade stand, helping us handle problems and remember important things that happen in our app.
In this blog, we’ll learn how to:
- Catch problems when they happen (Error Handling).
- Write down important events (Logging).
- Prepare for NestJS-related interview questions!
Table of Contents
What is Error Handling?
Error handling is like a safety net for your app. If something breaks, NestJS catches it and tells you what went wrong instead of just stopping everything.
Example:
If someone orders “pineapple lemonade” at your stand, but you only sell “lemon lemonade,” your app should say:
“Sorry, we don’t have that. Try something else!”
How to Handle Errors in NestJS
- Using Built-in Exceptions
NestJS has ready-made error responses.
BadRequestException
: When the customer orders something invalid.NotFoundException
: When the menu item doesn’t exist.
import { BadRequestException, NotFoundException } from '@nestjs/common';
throw new BadRequestException('This item is not on the menu!');
- Custom Error Messages
Want to use your own words? You can customize the message:
throw new NotFoundException('Oops! Lemonades are sold out!');
- Global Exception Filters
Think of this as a “manager” that handles all errors for you.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
@Catch(HttpException)
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
const status = exception.getStatus();
response.status(status).json({
message: exception.message || 'Something went wrong!',
});
}
}
What is Logging?
Logging is like keeping a diary of what happens in your app. Did you make a sale? Did something go wrong? Write it down so you can learn from it later.
How to Log in NestJS
- Using NestJS Logger
NestJS comes with a built-in logger to make it easy!
import { Logger } from '@nestjs/common';
const logger = new Logger('AppLogger');
logger.log('We sold lemonade!');
logger.error('Customer complained about the lemonade!');
logger.warn('We’re running low on lemons!');
- Custom Logging Service
You can create your own logging service to store logs in a file or database.
import { Injectable, LoggerService } from '@nestjs/common';
@Injectable()
export class CustomLogger implements LoggerService {
log(message: string) {
console.log(`LOG: ${message}`);
}
error(message: string) {
console.error(`ERROR: ${message}`);
}
warn(message: string) {
console.warn(`WARNING: ${message}`);
}
}
Why Error Handling and Logging are Important
- Fixing Problems Quickly: Logs help you understand what went wrong.
- Improving User Experience: Users see friendly error messages instead of crashes.
- Building Trust: A well-maintained app shows professionalism.
Interview Questions and Answers
- What is the purpose of Exception Filters in NestJS?
Answer: Exception Filters handle errors globally or locally in NestJS. They catch exceptions and format the response sent to the user. - How do you use the built-in Logger in NestJS?
Answer: You can import theLogger
class from@nestjs/common
and use methods likelog
,error
, andwarn
to log information. - What’s the difference between HTTP Exceptions and Custom Exceptions?
Answer: HTTP Exceptions are predefined in NestJS, likeBadRequestException
, while Custom Exceptions let you create your own error messages and logic. - How can you save logs to a file in NestJS?
Answer: You can use libraries likewinston
to extend NestJS logging capabilities and save logs to a file.
Companies That Ask About This Topic
- Microsoft
- Globant
- Infosys
- Accenture
- Amazon
These companies often evaluate your understanding of maintaining reliable and scalable systems, making error handling and logging critical topics.
Conclusion
Error handling and logging are like the heartbeat of any app. They make sure your NestJS app doesn’t just survive but thrives, even when things go wrong. Whether you’re a kid running a lemonade stand or a developer building apps, these concepts are easy to learn and super important!
Happy coding! 🚀