亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何處理 NestJS 中的 TypeORM 錯誤?

如何處理 NestJS 中的 TypeORM 錯誤?

神不在的星期二 2022-01-07 21:14:45
我想創建一個自定義異常過濾器來處理不同類型的 TypeORM 錯誤。我查看了TypeORM 錯誤類,似乎 TypeORM 中沒有像MongoError這樣的東西。我想做一些類似于1FpGLLjZSZMx6k 的答案的東西,這就是我到目前為止所做的。import { QueryFailedError } from 'typeorm';@Catch(QueryFailedError)export class QueryFailedExceptionFilter implements ExceptionFilter {  catch(exception: QueryFailedError, host: ArgumentsHost) {    const context = host.switchToHttp();    const response = context.getResponse<Response>();    const request = context.getRequest<Request>();    const { url } = request;    const { name } = exception;    const errorResponse = {      path: url,      timestamp: new Date().toISOString(),      message: name,    };    response.status(HttpStatus.BAD_REQUEST).json(errorResponse);  }}例如,如果我需要捕獲另一個錯誤EntityNotFoundError,我必須編寫相同的代碼,這是一項非常繁瑣的任務。如果我可以通過如下所示的單個過濾器處理錯誤,那就太好了。有任何想法嗎?@Catch(TypeORMError)export class EntityNotFoundExceptionFilter implements ExceptionFilter {  catch(exception: MongoError, host: ArgumentsHost) {    switch (exception.code) {      case some error code:        // handle error    }  }}
查看完整描述

2 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

文檔中,它說:

@Catch()裝飾可以采用單個參數,或逗號分隔的列表。這使您可以一次為多種類型的異常設置過濾器。

所以在你的情況下,你可以寫:

@Catch(QueryFailedError, EntityNotFoundError)


查看完整回答
反對 回復 2022-01-07
?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

要處理不同類型的 TypeOrm 錯誤,如果異常構造函數匹配任何 TypeOrm 錯誤(來自 node_modules\typeorm\error),您可以切換/ case。此外, (exception as any).code 將提供發生的實際數據庫錯誤。注意 @catch() 裝飾器是空的,以便捕獲所有錯誤類型。


import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';

import { Request, Response } from 'express';

import { QueryFailedError, EntityNotFoundError, CannotCreateEntityIdMapError } from 'typeorm';

import { GlobalResponseError } from './global.response.error';


@Catch()

export class GlobalExceptionFilter implements ExceptionFilter {

    catch(exception: unknown, host: ArgumentsHost) {

        const ctx = host.switchToHttp();

        const response = ctx.getResponse<Response>();

        const request = ctx.getRequest<Request>();

        let message = (exception as any).message.message;

        let code = 'HttpException';


        Logger.error(message, (exception as any).stack, `${request.method} ${request.url}`);


        let status = HttpStatus.INTERNAL_SERVER_ERROR;

        

        switch (exception.constructor) {

            case HttpException:

                status = (exception as HttpException).getStatus();

                break;

            case QueryFailedError:  // this is a TypeOrm error

                status = HttpStatus.UNPROCESSABLE_ENTITY

                message = (exception as QueryFailedError).message;

                code = (exception as any).code;

                break;

            case EntityNotFoundError:  // this is another TypeOrm error

                status = HttpStatus.UNPROCESSABLE_ENTITY

                message = (exception as EntityNotFoundError).message;

                code = (exception as any).code;

                break;

            case CannotCreateEntityIdMapError: // and another

                status = HttpStatus.UNPROCESSABLE_ENTITY

                message = (exception as CannotCreateEntityIdMapError).message;

                code = (exception as any).code;

                break;

            default:

                status = HttpStatus.INTERNAL_SERVER_ERROR

        }


        response.status(status).json(GlobalResponseError(status, message, code, request));

    }

}



import { Request } from 'express';

import { IResponseError } from './response.error.interface';


export const GlobalResponseError: (statusCode: number, message: string, code: string, request: Request) => IResponseError = (

    statusCode: number,

    message: string,

    code: string,

    request: Request

): IResponseError => {

    return {

        statusCode: statusCode,

        message,

        code,

        timestamp: new Date().toISOString(),

        path: request.url,

        method: request.method

    };

};



export interface IResponseError {

    statusCode: number;

    message: string;

    code: string;

    timestamp: string;

    path: string;

    method: string;

}


查看完整回答
反對 回復 2022-01-07
  • 2 回答
  • 0 關注
  • 744 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號