Discover how one simple tool can save you from endless repetitive code and bugs!
Why interceptors add cross-cutting logic in NestJS - The Real Reasons
Imagine you have to add logging, error handling, and timing to every function in your NestJS app manually by writing the same code inside each controller or service method.
Manually adding these repeated tasks everywhere makes your code messy, hard to maintain, and easy to forget or make mistakes. It slows you down and causes bugs.
Interceptors let you write this shared logic once and apply it automatically across many parts of your app, keeping your code clean and consistent.
async getData() {
console.log('Start');
try {
const result = await this.service.fetch();
console.log('End');
return result;
} catch (e) {
console.error(e);
throw e;
}
}@UseInterceptors(LoggingInterceptor)
async getData() {
return this.service.fetch();
}You can add or change shared behaviors like logging, caching, or error handling in one place and have it affect your whole app automatically.
In a real app, you might want to log every request's duration to find slow endpoints without touching each controller method.
Manual repetition of shared logic is error-prone and hard to maintain.
Interceptors centralize cross-cutting concerns for cleaner code.
This makes your app easier to update and debug.