Study
NestJS

Exception Filters

Penjelasan

NestJS punya built-in exception handling (mis. throw new NotFoundException() otomatis jadi response 404 terformat) — untuk kustomisasi format error lebih jauh, dibuat Exception Filter: class mengimplementasikan ExceptionFilter, ditandai @Catch(TipeException), dipasang lewat @UseFilters() atau global di main.ts.

Contoh Konsep

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const status = exception.getStatus();

        response.status(status).json({
            success: false,
            timestamp: new Date().toISOString(),
            message: exception.message,
        });
    }
}

// Dipakai: @UseFilters(HttpExceptionFilter) di atas Controller/method

Praktikum

Buat NotFoundExceptionFilter dengan @Catch(NotFoundException) yang merespons format { success: false, error: pesan, waktu: ISO timestamp }.

Editor Latihan

Ketik/edit bebas di sini untuk latihan — kode ini tidak dijalankan.

Tips

Exception Filter yang di-@Catch(HttpException) HANYA menangkap exception NestJS bawaan (NotFoundException, BadRequestException, dst, semua turunan HttpException) — error JavaScript biasa (mis. TypeError dari bug kode) TIDAK ikut tertangkap kecuali kamu pakai @Catch() TANPA argumen sama sekali untuk menangkap SEMUA jenis error.