Skip to content

Commit

Permalink
fix(core): Change BaseExceptionFilter to only handle REST calls
Browse files Browse the repository at this point in the history
  • Loading branch information
nirga committed Dec 17, 2020
1 parent 3a700e2 commit 0d8954d
Showing 1 changed file with 30 additions and 20 deletions.
50 changes: 30 additions & 20 deletions packages/core/exceptions/base-exception-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -27,30 +28,39 @@ export class BaseExceptionFilter<T = any> implements ExceptionFilter<T> {
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,
Expand Down

0 comments on commit 0d8954d

Please sign in to comment.