Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return relevant error code in logger interceptor #2245

Merged
merged 2 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/routes/common/interceptors/route-logger.interceptor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { RouteLoggerInterceptor } from '@/routes/common/interceptors/route-logge
import { Server } from 'net';
import { ValidationPipe } from '@/validation/pipes/validation.pipe';
import { NumericStringSchema } from '@/validation/entities/schemas/numeric-string.schema';
import { ZodError } from 'zod';

// We expect 500 instead of the status code of the DataSourceError
// The reason is that this test webserver does not have logic to map
Expand Down Expand Up @@ -62,6 +63,11 @@ class TestController {
): void {}
/* eslint-enable @typescript-eslint/no-unused-vars */

@Get('zod-error')
zodError(): never {
throw new ZodError([]);
}

@Get('error-level-info-with-code')
errorLevelInfoWithCode(): void {
throw new ErrorWithCode('error', 430);
Expand Down Expand Up @@ -233,6 +239,29 @@ describe('RouteLoggerInterceptor tests', () => {
expect(mockLoggingService.warn).not.toHaveBeenCalled();
});

it('400 Zod error triggers info level', async () => {
await request(app.getHttpServer())
.get('/test/zod-error')
.expect(expectedDatasourceErrorCode);

expect(mockLoggingService.error).toHaveBeenCalledTimes(1);
expect(mockLoggingService.error).toHaveBeenCalledWith({
chain_id: null,
client_ip: null,
detail: '[]',
method: 'GET',
path: '/test/zod-error',
response_time_ms: expect.any(Number),
route: '/test/zod-error',
safe_app_user_agent: null,
status_code: 502,
origin: null,
});
expect(mockLoggingService.info).not.toHaveBeenCalled();
expect(mockLoggingService.debug).not.toHaveBeenCalled();
expect(mockLoggingService.warn).not.toHaveBeenCalled();
});

it('400 Any error triggers info level', async () => {
await request(app.getHttpServer())
.get('/test/error-level-info-with-code')
Expand Down
20 changes: 8 additions & 12 deletions src/routes/common/interceptors/route-logger.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ import { ILoggingService, LoggingService } from '@/logging/logging.interface';
import { Inject } from '@nestjs/common/decorators';
import { Observable, tap } from 'rxjs';
import { formatRouteLogMessage } from '@/logging/utils';
import { DataSourceError } from '@/domain/errors/data-source.error';
import { Request, Response } from 'express';
import isNumber from 'lodash/isNumber';
import { ZodErrorWithCode } from '@/validation/pipes/validation.pipe';
import { ZodError } from 'zod';

/**
* The {@link RouteLoggerInterceptor} is an interceptor that logs the requests
Expand Down Expand Up @@ -64,17 +63,14 @@ export class RouteLoggerInterceptor implements NestInterceptor {
* @private
*/
private onError(request: Request, error: Error, startTimeMs: number): void {
let statusCode;
if (error instanceof HttpException) {
statusCode = error.getStatus();
} else if (error instanceof DataSourceError) {
statusCode = error.code ?? HttpStatus.INTERNAL_SERVER_ERROR;
} else if (error instanceof ZodErrorWithCode) {
statusCode = error.code;
} else if ('code' in error && isNumber(error.code)) {
let statusCode: number = HttpStatus.INTERNAL_SERVER_ERROR;
if ('code' in error && isNumber(error.code)) {
statusCode = error.code;
} else {
statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
} else if (error instanceof HttpException) {
statusCode = error.getStatus();
} else if (error instanceof ZodError) {
// Since we mainly use Zod for Datasource validation, we should throw a 502 Bad Gateway instead of a 422 Unprocessable Entity
statusCode = HttpStatus.BAD_GATEWAY;
}

const message = formatRouteLogMessage(
Expand Down
Loading