From 9bf75614e2f470f97b44d376003625df30a6a78f Mon Sep 17 00:00:00 2001 From: David Mehren Date: Thu, 23 Sep 2021 22:05:57 +0200 Subject: [PATCH] Log errors in ValidationPipe Previously, when an error was encountered while validating the request, only an HTTP 400 status code was returned to the client. This adds logging of the error message, so invalid requests can be debugged. Signed-off-by: David Mehren --- src/main.ts | 11 +++-------- src/utils/setup-pipes.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) create mode 100644 src/utils/setup-pipes.ts diff --git a/src/main.ts b/src/main.ts index 289138a13..1a9048bb6 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: AGPL-3.0-only */ -import { LogLevel, ValidationPipe } from '@nestjs/common'; +import { LogLevel } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; @@ -15,6 +15,7 @@ import { MediaConfig } from './config/media.config'; import { ConsoleLoggerService } from './logger/console-logger.service'; import { BackendType } from './media/backends/backend-type.enum'; import { setupSessionMiddleware } from './utils/session'; +import { setupValidationPipe } from './utils/setup-pipes'; import { setupPrivateApiDocs, setupPublicApiDocs } from './utils/swagger'; async function bootstrap(): Promise { @@ -55,13 +56,7 @@ async function bootstrap(): Promise { }); logger.log(`Enabling CORS for '${appConfig.rendererOrigin}'`, 'AppBootstrap'); - app.useGlobalPipes( - new ValidationPipe({ - forbidUnknownValues: true, - skipMissingProperties: false, - transform: true, - }), - ); + app.useGlobalPipes(setupValidationPipe(logger)); if (mediaConfig.backend.use === BackendType.FILESYSTEM) { logger.log( `Serving the local folder '${mediaConfig.backend.filesystem.uploadPath}' under '/uploads'`, diff --git a/src/utils/setup-pipes.ts b/src/utils/setup-pipes.ts new file mode 100644 index 000000000..e87f125b1 --- /dev/null +++ b/src/utils/setup-pipes.ts @@ -0,0 +1,29 @@ +/* + * SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file) + * + * SPDX-License-Identifier: AGPL-3.0-only + */ +import { BadRequestException, ValidationPipe } from '@nestjs/common'; + +import { ConsoleLoggerService } from '../logger/console-logger.service'; + +export function setupValidationPipe( + logger: ConsoleLoggerService, +): ValidationPipe { + return new ValidationPipe({ + forbidUnknownValues: true, + skipMissingProperties: false, + transform: true, + exceptionFactory: (errors): BadRequestException => { + // strip the trailing newline for cleaner logs + const errorMessage = errors.toString().trimEnd(); + logger.debug( + `Errors were encountered while validating a request:\n${errorMessage}`, + 'ValidationPipe', + ); + return new BadRequestException( + 'Encountered an exception while validating the request.', + ); + }, + }); +}