0
0
NestJSframework~5 mins

Logging exceptions in NestJS

Choose your learning style9 modes available
Introduction

Logging exceptions helps you find and fix problems in your app quickly. It keeps a record of errors so you can understand what went wrong.

When you want to track errors happening in your NestJS app.
When you need to debug issues reported by users.
When you want to monitor app health and catch bugs early.
When you want to save error details for later analysis.
When you want to improve app reliability by fixing logged errors.
Syntax
NestJS
import { Logger } from '@nestjs/common';

try {
  // code that might throw
} catch (error) {
  Logger.error('Error message', error.stack);
}

Use Logger.error to log exceptions with a message and stack trace.

Import Logger from @nestjs/common to use NestJS built-in logging.

Examples
This logs a simple error with a message and the error stack.
NestJS
import { Logger } from '@nestjs/common';

try {
  throw new Error('Oops!');
} catch (error) {
  Logger.error('Caught an error', error.stack);
}
You can add a context string like 'MyApp' to identify where the error happened.
NestJS
import { Logger } from '@nestjs/common';

try {
  // some risky code
} catch (error) {
  Logger.error('Failed to process request', error.stack, 'MyApp');
}
Sample Program

This example shows how to catch an exception from a function and log it with a message, stack trace, and context.

NestJS
import { Logger } from '@nestjs/common';

function riskyOperation() {
  throw new Error('Something bad happened');
}

try {
  riskyOperation();
} catch (error) {
  Logger.error('Exception caught in riskyOperation', error.stack, 'AppModule');
}
OutputSuccess
Important Notes

Always log the stack trace to understand where the error happened.

Use context strings to make logs easier to search and filter.

Consider using custom exception filters in NestJS for centralized logging.

Summary

Logging exceptions helps track and fix errors in your app.

Use Logger.error with message, stack, and optional context.

Catch errors and log them to keep a clear error history.