Error Handling and Logging in NestJS Applications

Error Handling and Logging in NestJS Applications

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:

  1. Catch problems when they happen (Error Handling).
  2. Write down important events (Logging).
  3. Prepare for NestJS-related interview questions!

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

  1. 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!');
  1. Custom Error Messages
    Want to use your own words? You can customize the message:
throw new NotFoundException('Oops! Lemonades are sold out!');
  1. 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

  1. 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!');
  1. 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

  1. Fixing Problems Quickly: Logs help you understand what went wrong.
  2. Improving User Experience: Users see friendly error messages instead of crashes.
  3. Building Trust: A well-maintained app shows professionalism.

Interview Questions and Answers

  1. 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.
  2. How do you use the built-in Logger in NestJS?
    Answer: You can import the Logger class from @nestjs/common and use methods like log, error, and warn to log information.
  3. What’s the difference between HTTP Exceptions and Custom Exceptions?
    Answer: HTTP Exceptions are predefined in NestJS, like BadRequestException, while Custom Exceptions let you create your own error messages and logic.
  4. How can you save logs to a file in NestJS?
    Answer: You can use libraries like winston 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! 🚀

Interested in learning more about Microservices and NestJS? Check out our latest blogs for more in-depth guides, tutorials, and best practices on building scalable applications with NestJS and microservices.

Leave a Reply

Your email address will not be published. Required fields are marked *