mirror of
https://github.com/dadosfera/maestro.git
synced 2026-08-31 19:58:21 +00:00
Merge pull request #119 from dadosfera/fix/error-handling
FIX: added exception filter to catch unhandled errors
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
import ErrorBuilder from '../utils/ErrorBuilder';
|
||||
|
||||
@Catch(Error)
|
||||
export class GrpcToHttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: any, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
|
||||
// return this exception directly if is already of type ErrorBuilder,
|
||||
// else transform it using the ErrorBuilder
|
||||
const err =
|
||||
exception.constructor.name === ErrorBuilder.name
|
||||
? exception
|
||||
: new ErrorBuilder(exception.details);
|
||||
|
||||
const { statusCode } = err.response;
|
||||
return response.status(statusCode).json(err.response);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import {
|
||||
@@ -22,8 +23,10 @@ import {
|
||||
|
||||
import { AuthClientService } from './auth.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { GrpcToHttpExceptionFilter } from '../../error/grpc-to-http-exception.filter';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@UseFilters(new GrpcToHttpExceptionFilter())
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
logger: any;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { RpcException } from '@nestjs/microservices';
|
||||
|
||||
import ErrorCodes from './errorCodes';
|
||||
|
||||
function enrichErrorCode(code: string) {
|
||||
export function EnrichErrorCode(code: string) {
|
||||
switch (code) {
|
||||
case ErrorCodes.AUTH.WRONG_CREDENTIALS:
|
||||
return {
|
||||
@@ -138,7 +138,7 @@ export default class ErrorBuilder extends HttpException {
|
||||
logger.log(code);
|
||||
}
|
||||
|
||||
const { statusCode, message, error, code: rCode } = enrichErrorCode(code);
|
||||
const { statusCode, message, error, code: rCode } = EnrichErrorCode(code);
|
||||
super({ statusCode, message, error, code: rCode }, statusCode);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user