NestJS Enterprise Backend APIs · บทเรียน

การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์

นำตัวกรองข้อยกเว้นแบบกำหนดเองมาใช้เพื่อจัดการข้อผิดพลาดอย่างเหมาะสม และใช้อินเตอร์เซปเตอร์เพื่อแปลงผลตอบกลับหรือบันทึกคำขอ

บทเรียน 3 จาก 312 ขั้นตอน

การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์ เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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()) in main.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 data object).
  • 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.

เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
20
บทเรียน
76

คำถามที่พบบ่อย

บทเรียน “การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์”

นำตัวกรองข้อยกเว้นแบบกำหนดเองมาใช้เพื่อจัดการข้อผิดพลาดอย่างเหมาะสม และใช้อินเตอร์เซปเตอร์เพื่อแปลงผลตอบกลับหรือบันทึกคำขอ คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน

บทเรียน “การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม

ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เส้นทางและการจัดการคำขอ
  2. การดำเนินการ CRUD ด้วย TypeORM
  3. การจัดการข้อผิดพลาดและอินเตอร์เซปเตอร์
← กลับไปที่ NestJS Enterprise Backend APIs