Consider this NestJS service method that throws an exception and logs it using the Logger service:
import { Logger } from '@nestjs/common';
const logger = new Logger('MyService');
function riskyOperation() {
try {
throw new Error('Something went wrong');
} catch (error) {
logger.error('Operation failed', error.stack);
}
}
riskyOperation();What will be the output in the console?
import { Logger } from '@nestjs/common'; const logger = new Logger('MyService'); function riskyOperation() { try { throw new Error('Something went wrong'); } catch (error) { logger.error('Operation failed', error.stack); } } riskyOperation();
Remember that logger.error logs messages with the ERROR level.
The Logger.error method logs messages with the ERROR level, so the output prefix is [MyService] ERROR. The message and the error stack are printed.
In NestJS, you want to catch all exceptions thrown anywhere in your app and log them centrally. Which built-in class should you extend or use?
Think about the class designed to handle exceptions.
The ExceptionFilter class is designed to catch exceptions globally or locally and can be used to log errors centrally.
You want to log exceptions to a file instead of the console in a NestJS app. Which approach is correct?
Think about how to customize logging behavior in NestJS.
NestJS Logger does not support file logging out of the box. You must create a custom LoggerService that implements the LoggerService interface and override methods like error() to write logs to a file.
You use logger.error('Failed', error.message) inside a catch block, but the stack trace is missing in logs. Why?
Check what property contains the stack trace.
The error.message is just the error text. The stack trace is in error.stack. Passing error.message to logger.error will not show the stack trace.
Put these steps in the correct order to set up global exception logging in a NestJS app.
Think about class creation, dependency injection, method override, then registration.
First create the filter class (1), then inject Logger in constructor (4), override catch() to log (2), and finally register globally (3).