2024/11/13

Nestjs 透過Exception攔截找不到API問題

要在Nestjs攔截API或url找不到問題可以透過Exception或Middleware的方式實現
先安裝express
pnpm i @types/express express -D

代碼如下

import {
    ArgumentsHost,
    Catch,
    ExceptionFilter,
    NotFoundException
} from '@nestjs/common'
import { Request, Response } from 'express'

/**
 * Filter to catch not found exceptions
 * @class {NotFoundFilter}
 * @implements {ExceptionFilter}
 */
@Catch()
export class NotFoundFilter implements ExceptionFilter {
    /**
     * Catch the exception
     * @param exception {NotFoundException}
     * @param host {ArgumentsHost}
     * @return {Promise}
     */
    catch(
        exception: NotFoundException,
        host: ArgumentsHost
    ): Promise {
        // 取得Http的上下文
        const ctx = host.switchToHttp()
        // 取得Response
        const response = ctx.getResponse()
        //取得Request
        const request = ctx.getRequest()
        // 取得使用者語系
        const lang = request.headers['lang'] as string
        // 取得錯誤訊息
        const errorResponse = {
            msg: 'API route not found',
            err: true
        }

        // 透過Response回傳錯誤訊息
        response.status(200).json(errorResponse)
    }
}

記得要在listen前加入這段代碼
    // 設定API找不到的Filter
    app.useGlobalFilters(new NotFoundFilter())