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 <git@herrmehren.de>
This commit is contained in:
David Mehren 2021-09-23 22:05:57 +02:00
parent b2ae4a85c3
commit 9bf75614e2
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
2 changed files with 32 additions and 8 deletions

View file

@ -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<void> {
@ -55,13 +56,7 @@ async function bootstrap(): Promise<void> {
});
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'`,

29
src/utils/setup-pipes.ts Normal file
View file

@ -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.',
);
},
});
}