some error handler + error validation + realEstate bug fixed for hamta end moallem

This commit is contained in:
2026-06-14 12:16:48 +03:30
parent 2cb3340f40
commit b629a47f7f
14 changed files with 299 additions and 39 deletions
+6
View File
@@ -16,4 +16,10 @@ export class NormalizedErrorDto {
@ApiPropertyOptional({ example: '503' })
providerCode?: string;
@ApiPropertyOptional({
example: [{ field: 'sheba', constraints: ['sheba must start with IR and contain 24 digits'] }],
description: 'Field-level validation errors when code is VALIDATION_ERROR',
})
details?: Array<{ field: string; constraints: string[] }>;
}
+15 -4
View File
@@ -10,6 +10,7 @@ import { Request, Response } from 'express';
import { BaseInquiryResponseDto } from '../dto/base-inquiry-response.dto';
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
import { ProviderException } from '../exceptions/provider.exception';
import { isNormalizedError } from '../helpers/validation-error.helper';
/**
* Global exception filter — normalizes all errors into BaseInquiryResponseDto
@@ -22,7 +23,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request & { trackingCode?: string }>();
const request = ctx.getRequest<Request & { requestId?: string; trackingCode?: string }>();
const status =
exception instanceof HttpException
@@ -31,9 +32,10 @@ export class AllExceptionsFilter implements ExceptionFilter {
const normalizedError = this.extractNormalizedError(exception);
const trackingCode = request.trackingCode ?? 'UNKNOWN';
const requestId = request.requestId ?? (request.headers['x-request-id'] as string | undefined) ?? 'unknown';
this.logger.error(
`requestId=${request.headers['x-request-id']} | trackingCode=${trackingCode} | ${normalizedError.message}`,
`requestId=${requestId} | trackingCode=${trackingCode} | code=${normalizedError.code} | ${normalizedError.message}`,
exception instanceof Error ? exception.stack : undefined,
);
@@ -56,13 +58,22 @@ export class AllExceptionsFilter implements ExceptionFilter {
if (exception instanceof HttpException) {
const res = exception.getResponse();
if (typeof res === 'object' && res !== null && 'error' in res) {
return (res as { error: NormalizedErrorDto }).error;
if (typeof res === 'object' && res !== null) {
if ('error' in res && isNormalizedError((res as { error: unknown }).error)) {
return (res as { error: NormalizedErrorDto }).error;
}
if (isNormalizedError(res)) {
return res;
}
}
const message =
typeof res === 'string'
? res
: (res as { message?: string | string[] }).message;
return {
code: 'HTTP_ERROR',
message: Array.isArray(message) ? message.join(', ') : String(message ?? exception.message),
@@ -0,0 +1,97 @@
import { ValidationError } from 'class-validator';
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
export interface ValidationFieldError {
field: string;
constraints: string[];
}
export function flattenValidationErrors(
errors: ValidationError[],
parentPath = '',
): ValidationFieldError[] {
const result: ValidationFieldError[] = [];
for (const error of errors) {
const field = parentPath ? `${parentPath}.${error.property}` : error.property;
if (error.constraints) {
result.push({
field,
constraints: Object.values(error.constraints),
});
}
if (error.children?.length) {
result.push(...flattenValidationErrors(error.children, field));
}
}
return result;
}
export function buildValidationErrorResponse(errors: ValidationError[]): {
normalizedError: NormalizedErrorDto;
details: ValidationFieldError[];
} {
const details = flattenValidationErrors(errors);
const summary =
details.length > 0
? details.map((d) => `${d.field}: ${d.constraints.join(', ')}`).join('; ')
: 'Request validation failed';
return {
normalizedError: {
code: 'VALIDATION_ERROR',
message: summary,
details,
},
details,
};
}
export function formatHttpExceptionMessage(exception: unknown): string {
if (!(exception && typeof exception === 'object' && 'getResponse' in exception)) {
return exception instanceof Error ? exception.message : String(exception);
}
const response = (exception as { getResponse: () => unknown }).getResponse();
if (typeof response === 'string') {
return response;
}
if (typeof response !== 'object' || response === null) {
return exception instanceof Error ? exception.message : 'Request failed';
}
const body = response as {
message?: string | string[];
error?: unknown;
};
if (isNormalizedError(body.error)) {
return body.error.message;
}
if (Array.isArray(body.message)) {
return body.message.join('; ');
}
if (typeof body.message === 'string' && body.message.length > 0) {
return body.message;
}
return exception instanceof Error ? exception.message : 'Request failed';
}
export function isNormalizedError(value: unknown): value is NormalizedErrorDto {
return (
typeof value === 'object' &&
value !== null &&
'code' in value &&
'message' in value &&
typeof (value as NormalizedErrorDto).code === 'string' &&
typeof (value as NormalizedErrorDto).message === 'string'
);
}
@@ -6,6 +6,7 @@ import {
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { RequestLogger } from '../helpers/request-logger.helper';
import { formatHttpExceptionMessage } from '../helpers/validation-error.helper';
/**
* Logs HTTP request duration at the controller boundary.
@@ -31,9 +32,10 @@ export class LoggingInterceptor implements NestInterceptor {
);
},
error: (err: unknown) => {
const detail = formatHttpExceptionMessage(err);
this.requestLogger.logFailure(
{ requestId: req.requestId ?? 'unknown', durationMs: Date.now() - start },
`${req.method} ${req.url} failed`,
`${req.method} ${req.url} failed: ${detail}`,
err,
);
},