오류 처리와 인터셉터
원활한 오류 처리를 위해 사용자 정의 예외 필터를 구현하고, 인터셉터를 사용하여 응답을 변환하거나 요청을 기록합니다.
오류 처리와 인터셉터은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.
자주 묻는 질문
“오류 처리와 인터셉터” 강의는 무료인가요?
네 — “오류 처리와 인터셉터” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
“오류 처리와 인터셉터”에서 뭘 배우나요?
원활한 오류 처리를 위해 사용자 정의 예외 필터를 구현하고, 인터셉터를 사용하여 응답을 변환하거나 요청을 기록합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 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 작업
- 오류 처리와 인터셉터