UNPKG

@takentrade/takentrade-libs

Version:
57 lines (56 loc) 2.59 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpExceptionFilter = void 0; const common_1 = require("@nestjs/common"); let HttpExceptionFilter = class HttpExceptionFilter { catch(exception, host) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const status = exception instanceof common_1.HttpException ? exception.getStatus() : common_1.HttpStatus.INTERNAL_SERVER_ERROR; const message = exception instanceof common_1.HttpException ? exception.message : 'Sorry, something went wrong. Please try again later'; const responseObj = { success: false, message, statusCode: status, errors: this.getValidationErrors(exception) || [], timestamp: new Date().toLocaleString(), path: request.url, method: request.method, }; common_1.Logger.error(exception); common_1.Logger.verbose(this.logError(responseObj, request, exception)); response.status(status).send(responseObj); } getValidationErrors(exception) { if (exception instanceof common_1.BadRequestException) { const message = exception?.getResponse(); if (typeof message === 'object') { return message.errors; } } return []; } logError(errResponse, request, exception) { const { statusCode, error } = errResponse; const { method, url } = request; const errorLog = `Response Code: ${statusCode} - Method: ${method} URL - ${url} \n ${JSON.stringify(exception)} \n ${exception instanceof common_1.HttpException ? exception.stack : error} `; return errorLog; } }; exports.HttpExceptionFilter = HttpExceptionFilter; exports.HttpExceptionFilter = HttpExceptionFilter = __decorate([ (0, common_1.Catch)() ], HttpExceptionFilter);