NestJS 和 TypeORM 异常过滤器:获取状态不是函数

NestJS and TypeORM Exception Filter: Get Status is not a function

我正在使用 NestJS 和 TypeORM 开发应用程序。我的目标是捕获 TypeORM 错误,可以使用 exception filters.

来完成

但我的问题是,我遇到了这个错误:

(node:345) UnhandledPromiseRejectionWarning: TypeError: exception.getStatus is not a function

这与 github post 讨论 problem 类似,但它对我不起作用。

这是我的设置:

@Catch(QueryFailedError)
export class TypeORMQueryExceptionFilter 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(); //error here
....

我已经在全球范围内宣布了这一点,

main.ts

app.useGlobalFilters(new TypeORMQueryExceptionFilter())

app.module.ts

....
providers: [

        {
            provide: APP_FILTER,
            useClass: TypeORMQueryExceptionFilter
        }
    ]
...

如果您有解决为什么 getStatus() 的 HttpException 未定义的想法,那将是一个很大的帮助。

更新

由于这一行表明 catch(exception: HttpException, host: ArgumentsHost) { 相对于 @Catch(QueryFailedError),我可以假设 HttpException 是参数异常的错误类型。如果有的话,应该是catch(exception: QueryFailedError, host: ArgumentsHost) {

因此,由于 QueryFailedError 数据结构是这样的:

export declare class QueryFailedError extends TypeORMError {
    readonly query: string;
    readonly parameters: any[] | undefined;
    readonly driverError: any;
    constructor(query: string, parameters: any[] | undefined, driverError: any);
}

我认为不需要 const status = exception.getStatus();,因此我们可以将 const status = exception.getStatus() 重写或删除为 const status = exception.driverError()。这与示例 here.

有关

由于 QueryFailedError 在其属性中不表示任何 http 错误代码,因此一种解决方案可能必须像这样对 http 状态响应进行硬编码:

response
            .status(500)
            .json({
                statusCode: 500,
                timestamp: new Date().toISOString(),
                path: request.url,
            });

有人可以验证这一点吗,因为它可能是我做错了什么,因为 exception: HttpException 应该可以正常工作?

QueryFailedError 的实例没有方法 getStatus。修正过滤器的类型:

@Catch(QueryFailedError)
export class TypeORMQueryExceptionFilter implements ExceptionFilter {
    catch(exception: QueryFailedError, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();