错误处理与拦截器
实现自定义异常过滤器,以优雅地处理错误,并使用拦截器转换响应或记录请求。
错误处理与拦截器 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
Graceful API Error Handling
When building APIs, it's crucial to handle errors gracefully. Instead of crashing or returning vague messages, your API should provide clear, consistent feedback to clients.
This makes your API user-friendly and helps in debugging both client-side and server-side issues.
NestJS Built-in Exceptions
NestJS provides a set of standard HTTP exceptions, extending from HttpException. These exceptions map directly to common HTTP status codes.
BadRequestException(400)UnauthorizedException(401)NotFoundException(404)InternalServerErrorException(500)
Using these ensures your API speaks the standard HTTP language.
Throwing Built-in Exceptions
You can throw these exceptions directly from your controllers or services. NestJS's built-in exception layer will catch them and automatically format a standardized JSON error response.
Try running this example and access /greet/World (success) and /greet/error (error) to see the difference:
import { NestFactory } from '@nestjs/core';
import { Controller, Get, Param, NotFoundException, Module } from '@nestjs/common';
@Controller('greet')
class GreetController {
@Get(':name')
hello(@Param('name') name: string) {
if (name === 'error') {
throw new NotFoundException('Name "error" is not allowed!');
}
return `Hello, ${name}!`;
}
}
@Module({
controllers: [GreetController],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('App running on http://localhost:3000');
console.log('Try http://localhost:3000/greet/World');
console.log('Try http://localhost:3000/greet/error');
}
bootstrap();Custom Exception Filters
While built-in exceptions are useful, you might need more control over the error response format. This is where custom exception filters come in.
A custom filter lets you catch specific exceptions (or all exceptions) and define exactly what response is sent back to the client, including custom logging or integration with external services.
Building a Custom Filter
To create a custom filter, you implement the ExceptionFilter interface and decorate it with @Catch(), specifying the exception type(s) it should handle. Here's a basic example:
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class CustomHttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
customMessage: `An error occurred: ${exception.message}`,
});
}
}Applying Custom Filters
Once created, a custom filter needs to be applied. You can apply filters:
- Globally: Using
app.useGlobalFilters(new MyFilter())inmain.ts. - Controller-scoped: Using
@UseFilters(MyFilter)on a controller class. - Method-scoped: Using
@UseFilters(MyFilter)on a specific route handler method.
Global filters catch exceptions across your entire application, providing a consistent error structure.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; // Assume AppModule exists
import { CustomHttpExceptionFilter } from './custom-http-exception.filter'; // Assume filter exists
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new CustomHttpExceptionFilter());
await app.listen(3000);
}Introducing Interceptors
Interceptors are another powerful feature in NestJS, inspired by Aspect-Oriented Programming (AOP). They allow you to 'intercept' requests and responses, adding extra logic before or after a route handler executes.
Think of them as hooks into the request-response lifecycle, giving you fine-grained control.
Common Interceptor Uses
Interceptors are incredibly versatile and can be used for various purposes:
- Logging: Log request details, execution time, and responses.
- Transforming responses: Modify the outgoing data structure (e.g., wrap in a
dataobject). - Caching: Implement response caching for performance.
- Binding extra logic: Execute code before/after a method.
Logging Interceptor Example
Here's a simple interceptor that logs the time taken for a request to complete. It uses RxJS operators like tap and finalize to interact with the observable stream.
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap, finalize } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before request...');
const now = Date.now();
return next.handle().pipe(
tap(() => console.log(`After request... ${Date.now() - now}ms`)),
finalize(() => console.log('Request/response cycle finalized.'))
);
}
}Transforming Responses
Interceptors can also transform the data returned by your route handlers. This is common for standardizing API responses, for example, by wrapping all successful data in a data property to ensure consistency.
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
interface Response<T> {
data: T;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
return next.handle().pipe(map(data => ({ data })));
}
}Quick Check: Error vs Intercept
You've learned about both Exception Filters and Interceptors. Let's test your understanding of their primary roles.
Recap & Next Steps
In this lesson, we covered essential techniques for building robust NestJS APIs:
- Graceful Error Handling using built-in HTTP exceptions.
- Custom Exception Filters to customize error responses and handle specific exceptions.
- Interceptors for logging, transforming responses, and adding cross-cutting concerns.
Mastering these concepts will help you build professional, maintainable, and user-friendly APIs.
常见问题解答
「错误处理与拦截器」课时是免费的吗?
是的 — 「错误处理与拦截器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
「错误处理与拦截器」这节课中我会学到什么?
实现自定义异常过滤器,以优雅地处理错误,并使用拦截器转换响应或记录请求。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NestJS Enterprise Backend APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「错误处理与拦截器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?
能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 路由与请求处理
- 使用 TypeORM 执行 CRUD 操作
- 错误处理与拦截器