exception layer

{
"statusCode": 500,
"message": "Internal server error"
}throwing standard exceptions
* @example
* throw new HttpException()
* throw new HttpException('message', HttpStatus.BAD_REQUEST)
* throw new HttpException({ reason: 'this can be a human readable reason' }, HttpStatus.BAD_REQUEST)
* throw new HttpException(new Error('Cause Error'), HttpStatus.BAD_REQUEST)
* throw new HttpException('custom message', HttpStatus.BAD_REQUEST, {
* cause: new Error('Cause Error'),
* })
custom exceptions
export class AdditionalErrorsBadRequestException extends HttpException {
constructor(objectOrError: AdditionalExceptionError) {
super(HttpException.createBody(objectOrError), HttpStatus.BAD_REQUEST);
}
}built-in HTTP exceptions
BadRequestExceptionUnauthorizedExceptionNotFoundExceptionForbiddenExceptionNotAcceptableExceptionRequestTimeoutExceptionConflictExceptionGoneExceptionHttpVersionNotSupportedExceptionPayloadTooLargeExceptionUnsupportedMediaTypeExceptionUnprocessableEntityExceptionInternalServerErrorExceptionNotImplementedExceptionImATeapotExceptionMethodNotAllowedExceptionBadGatewayExceptionServiceUnavailableExceptionGatewayTimeoutExceptionPreconditionFailedExceptionException filters
@Catch(AdditionalErrorsBadRequestException)
export class AdditionalErrorsBadRequestExceptionFilter
extends ExceptionProvider
implements ExceptionFilter<BadRequestException>
{
constructor(
protected readonly slackService: SlackService,
httpResponseErrorMsg: HttpResponseErrorMsg,
) {
super(slackService, httpResponseErrorMsg);
}
catch(exception: BadRequestException, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const responseJson: ResponseJson = this.buildResponseJson(status);
const err = exception.getResponse() as ExceptionError & {
errorDetails: any;
};
responseJson.errors = [this.preProcessByClientError(err.message)];
responseJson.errorDetails = err.errorDetails;
response.status(status).json(responseJson);
}
}Arguments host
export interface ArgumentsHost {
/**
* Returns the array of arguments being passed to the handler.
*/
getArgs<T extends Array<any> = any[]>(): T;
/**
* Returns a particular argument by index.
* @param index index of argument to retrieve
*/
getArgByIndex<T = any>(index: number): T;
/**
* Switch context to RPC.
* @returns interface with methods to retrieve RPC arguments
*/
switchToRpc(): RpcArgumentsHost;
/**
* Switch context to HTTP.
* @returns interface with methods to retrieve HTTP arguments
*/
switchToHttp(): HttpArgumentsHost;
/**
* Switch context to WebSockets.
* @returns interface with methods to retrieve WebSockets arguments
*/
switchToWs(): WsArgumentsHost;
/**
* Returns the current execution context type (string)
*/
getType<TContext extends string = ContextType>(): TContext;
}ArgumentsHost에 [request, response]배열이 포함된다. 그러나 현재 컨텍스트가 웹 소켓 애플리케이션인 경우 해당 컨텍스트에 적합한 [client, data]배열이 포함된다.Binding filters
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);
}
bootstrap();Catch everything
import { Catch, ArgumentsHost } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
super.catch(exception, host);
}
}참고: https://dkrnfls.tistory.com/83, https://velog.io/@haron/NestJS-Lifecycle-Events