From 0d8954db003d7eb6e41551df5bb8e51dd388e4c7 Mon Sep 17 00:00:00 2001 From: Nir Gazit Date: Thu, 17 Dec 2020 19:46:10 +0200 Subject: [PATCH] fix(core): Change BaseExceptionFilter to only handle REST calls Fixes #5958 --- .../core/exceptions/base-exception-filter.ts | 50 +++++++++++-------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/packages/core/exceptions/base-exception-filter.ts b/packages/core/exceptions/base-exception-filter.ts index 3bf89e65459..579113e5390 100644 --- a/packages/core/exceptions/base-exception-filter.ts +++ b/packages/core/exceptions/base-exception-filter.ts @@ -9,6 +9,7 @@ import { Optional, } from '@nestjs/common'; import { isObject } from '@nestjs/common/utils/shared.utils'; +import { STATUS_CODES } from 'http'; import { AbstractHttpAdapter } from '../adapters'; import { MESSAGES } from '../constants'; import { HttpAdapterHost } from '../helpers'; @@ -27,30 +28,39 @@ export class BaseExceptionFilter implements ExceptionFilter { this.applicationRef || (this.httpAdapterHost && this.httpAdapterHost.httpAdapter); - if (!(exception instanceof HttpException)) { - return this.handleUnknownError(exception, host, applicationRef); + const { statusCode, message } = this.buildResponse(exception); + if (host.getType() == 'http') { + const ctx = host.switchToHttp(); + applicationRef.reply(ctx.getResponse(), message, statusCode); + } else { + // Let the RPC / GraphQL framework handle building the response. + throw exception; } - const res = exception.getResponse(); - const message = isObject(res) - ? res - : { - statusCode: exception.getStatus(), - message: res, - }; + } - applicationRef.reply(host.getArgByIndex(1), message, exception.getStatus()); + public buildResponse(exception: T) { + if (exception instanceof HttpException) { + const res = exception.getResponse(); + const message = isObject(res) + ? res + : { + statusCode: exception.getStatus(), + message: res, + }; + return { + statusCode: HttpStatus.INTERNAL_SERVER_ERROR, + message: message, + }; + } else { + this.logUnknownError(exception); + return { + statusCode: HttpStatus.INTERNAL_SERVER_ERROR, + message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE, + }; + } } - public handleUnknownError( - exception: T, - host: ArgumentsHost, - applicationRef: AbstractHttpAdapter | HttpServer, - ) { - const body = { - statusCode: HttpStatus.INTERNAL_SERVER_ERROR, - message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE, - }; - applicationRef.reply(host.getArgByIndex(1), body, body.statusCode); + public logUnknownError(exception: T) { if (this.isExceptionObject(exception)) { return BaseExceptionFilter.logger.error( exception.message,