From eb08739eea665119f35f41b2b38fea680795c07b Mon Sep 17 00:00:00 2001 From: allburov Date: Sat, 25 Nov 2023 18:06:22 +0700 Subject: [PATCH] [core] Send 404 if file does not exist fix #134 --- src/api/exception.filter.ts | 28 +++++++++++++++++++++++++++- src/main.ts | 1 - 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/api/exception.filter.ts b/src/api/exception.filter.ts index 673fa8b8..c1f56767 100644 --- a/src/api/exception.filter.ts +++ b/src/api/exception.filter.ts @@ -23,16 +23,42 @@ export function serializeError(err: unknown) { @Catch() export class AllExceptionsFilter implements ExceptionFilter { - catch(exception: HttpException | Error, host: ArgumentsHost): void { + catch(exception: any | Error, host: ArgumentsHost): void { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); + /** + * If file not found - we get weird 500 error + * So we convert that exception manually to 404 and send appropriate JSON response + * @issue https://github.com/devlikeapro/whatsapp-http-api/issues/134 + * @solution https://github.com/nestjs/serve-static/issues/139#issuecomment-612429557 + */ + if (exception.code === 'ENOENT') { + response.status(HttpStatus.NOT_FOUND).json({ + error: { + code: 404, + key: 'FILE_NOT_FOUND', + message: 'File not found', + details: 'File not found or no longer available', + }, + }); + response.send(); + return; + } + + /** + * If it's HttpException - pass it as is + */ if (exception instanceof HttpException) { response.status(exception.getStatus()).json(exception.getResponse()); return; } + /** + * If it's not HttpException - pass it as 500 error + * And send JSON response with error details + */ const httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.status(httpStatus).json({ statusCode: httpStatus, diff --git a/src/main.ts b/src/main.ts index eeedf124..afc6a1c6 100644 --- a/src/main.ts +++ b/src/main.ts @@ -7,7 +7,6 @@ import { AppModuleCore } from './core/app.module.core'; import { SwaggerModuleCore } from './core/swagger.module.core'; import { getWAHAVersion, VERSION, WAHAVersion } from './version'; import { WAHA_WEBHOOKS } from './structures/webhooks.dto'; -import { LogLevel } from '@nestjs/common'; import { getLogLevels } from './helpers'; async function loadModules(): Promise<