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

Time:04-11

I'm developing an app using NestJS and TypeORM. My goal is to catch TypeORM errors and it could be done using exception filters.

But my problem is, I'm encountering this error:

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

This is similar to this github post discussing the problem but it's not working on my end.

Here's my setup:

@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
....

I've declared this globally so,

main.ts

app.useGlobalFilters(new TypeORMQueryExceptionFilter())

app.module.ts

....
providers: [

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

If you have an idea resolving why getStatus() of HttpException is undefined, it would be a big help.

Update

As this line suggests catch(exception: HttpException, host: ArgumentsHost) { in relation to @Catch(QueryFailedError), I could assume that HttpException is the wrong type for param exception. It should be,if ever, catch(exception: QueryFailedError, host: ArgumentsHost) { instead.

Thus, since the QueryFailedError data structure is this:

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

I believe that const status = exception.getStatus(); is not needed so we could re-write or eliminate const status = exception.getStatus() to const status = exception.driverError(). This is relation to the example here.

Since QueryFailedError doesn't represent any http error codes in its properties, one solution could have to hard code the http status response like this:

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

Can someone validate this as it could be I just did something wrong as exception: HttpException should be working anyway?

CodePudding user response:

instances of QueryFailedError doesn't has the method getStatus. Fix the types of your filter:

@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>();
  • Related