forked from Shared/esg
feat: add Persian error translations and comprehensive test suite
Implement normalized error handling with Persian translations across all exception types, replace legacy NestJS exceptions with AppException, and add unit, integration, and smoke tests. - Add error catalog with gateway-owned codes and Persian messages - Introduce AppException wrapping normalized error envelopes - Add translateError helper for automatic messageFa population - Remove claims module and update provider error normalization - Add unit tests for error contracts and helper functions - Add integration tests for admin and inquiry endpoints - Add smoke tests for real provider connectivity - Add test support utilities (auth mocks, assertions, app factory)
This commit is contained in:
@@ -0,0 +1,374 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
|
||||
|
||||
export interface ErrorCatalogEntry {
|
||||
status: HttpStatus;
|
||||
message: string;
|
||||
messageFa: string;
|
||||
}
|
||||
|
||||
export const ERROR_CATALOG = {
|
||||
PROVIDER_TIMEOUT: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider request timed out',
|
||||
messageFa: 'درخواست به سرویسدهنده زمانبر شد',
|
||||
},
|
||||
PROVIDER_ERROR: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider request failed',
|
||||
messageFa: 'خطا در سرویسدهنده',
|
||||
},
|
||||
PROVIDER_NETWORK_ERROR: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider network request failed',
|
||||
messageFa: 'ارتباط با سرویسدهنده برقرار نشد',
|
||||
},
|
||||
PROVIDER_BAD_RESPONSE: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider returned an invalid response',
|
||||
messageFa: 'پاسخ سرویسدهنده معتبر نیست',
|
||||
},
|
||||
PROVIDER_AUTH_FAILED: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider authentication failed',
|
||||
messageFa: 'احراز هویت سرویسدهنده ناموفق بود',
|
||||
},
|
||||
PROVIDER_REJECTED: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider rejected the request',
|
||||
messageFa: 'سرویسدهنده درخواست را رد کرد',
|
||||
},
|
||||
NO_PROVIDERS: {
|
||||
status: HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
message: 'No enabled providers configured for this inquiry',
|
||||
messageFa: 'سرویسدهندهای برای این استعلام فعال نیست',
|
||||
},
|
||||
ALL_PROVIDERS_FAILED: {
|
||||
status: HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
message: 'All providers failed',
|
||||
messageFa: 'تمامی سرویسدهندهها با خطا مواجه شدند',
|
||||
},
|
||||
UNKNOWN_ERROR: {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: 'Unknown provider error',
|
||||
messageFa: 'خطای ناشناخته در سرویسدهنده',
|
||||
},
|
||||
UNSUPPORTED_INQUIRY: {
|
||||
status: HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
message: 'Provider does not support this inquiry type',
|
||||
messageFa: 'سرویسدهنده از این نوع استعلام پشتیبانی نمیکند',
|
||||
},
|
||||
API_ERROR: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Provider API request failed',
|
||||
messageFa: 'خطا در فراخوانی API سرویسدهنده',
|
||||
},
|
||||
HTTP_ERROR: {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: 'HTTP request failed',
|
||||
messageFa: 'درخواست ناموفق بود',
|
||||
},
|
||||
INTERNAL_ERROR: {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: 'Internal server error',
|
||||
messageFa: 'خطای داخلی سرور',
|
||||
},
|
||||
NETWORK_ERROR: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Network request failed',
|
||||
messageFa: 'خطا در اتصال به شبکه',
|
||||
},
|
||||
INQUIRY_FAILED: {
|
||||
status: HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
message: 'Inquiry failed',
|
||||
messageFa: 'استعلام با خطا مواجه شد',
|
||||
},
|
||||
INQUIRY_NO_MATCH: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'Inquiry returned no matching result',
|
||||
messageFa: 'نتیجهای مطابق با اطلاعات وارد شده یافت نشد',
|
||||
},
|
||||
RECORD_NOT_FOUND: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'Record not found',
|
||||
messageFa: 'رکوردی یافت نشد',
|
||||
},
|
||||
SAYAH_ERROR: {
|
||||
status: HttpStatus.BAD_GATEWAY,
|
||||
message: 'Sayah inquiry failed',
|
||||
messageFa: 'خطا در سرویس سیاح',
|
||||
},
|
||||
SHEBA_MISMATCH: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'Submitted sheba does not match inquiry result',
|
||||
messageFa: 'اطلاعات شبای وارد شده با نتیجه استعلام مطابقت ندارد',
|
||||
},
|
||||
VALIDATION_ERROR: {
|
||||
status: HttpStatus.BAD_REQUEST,
|
||||
message: 'Request validation failed',
|
||||
messageFa: 'اطلاعات وارد شده معتبر نیست',
|
||||
},
|
||||
INVALID_CREDENTIALS: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: 'Invalid credentials',
|
||||
messageFa: 'نام کاربری یا رمز عبور صحیح نیست',
|
||||
},
|
||||
ACCOUNT_INACTIVE: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Account is inactive',
|
||||
messageFa: 'حساب کاربری غیرفعال است',
|
||||
},
|
||||
ACCOUNT_BLOCKED: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Account is blocked',
|
||||
messageFa: 'حساب کاربری مسدود شده است',
|
||||
},
|
||||
INVALID_REFRESH_TOKEN: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: 'Invalid refresh token',
|
||||
messageFa: 'توکن نوسازی نامعتبر است',
|
||||
},
|
||||
API_KEY_NOT_CONFIGURED: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: 'API key authentication is not configured',
|
||||
messageFa: 'احراز هویت با کلید API پیکربندی نشده است',
|
||||
},
|
||||
INVALID_API_KEY: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: 'Invalid or missing API key',
|
||||
messageFa: 'کلید API نامعتبر است یا ارسال نشده است',
|
||||
},
|
||||
UNAUTHORIZED: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: 'Unauthorized',
|
||||
messageFa: 'احراز هویت انجام نشده است',
|
||||
},
|
||||
AUTHENTICATION_REQUIRED: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Authentication required',
|
||||
messageFa: 'احراز هویت الزامی است',
|
||||
},
|
||||
INSUFFICIENT_ROLE: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Insufficient role permissions',
|
||||
messageFa: 'سطح دسترسی کافی نیست',
|
||||
},
|
||||
INSUFFICIENT_USER_MANAGEMENT_PERMISSION: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Insufficient permissions to manage users',
|
||||
messageFa: 'دسترسی کافی برای مدیریت کاربران وجود ندارد',
|
||||
},
|
||||
SUPER_ADMIN_ROLE_REQUIRED: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Only SUPER_ADMIN can assign SUPER_ADMIN role',
|
||||
messageFa: 'فقط مدیر ارشد میتواند نقش مدیر ارشد را اختصاص دهد',
|
||||
},
|
||||
USER_NOT_FOUND: {
|
||||
status: HttpStatus.NOT_FOUND,
|
||||
message: 'User not found',
|
||||
messageFa: 'کاربر یافت نشد',
|
||||
},
|
||||
USERNAME_OR_EMAIL_EXISTS: {
|
||||
status: HttpStatus.CONFLICT,
|
||||
message: 'Username or email already exists',
|
||||
messageFa: 'نام کاربری یا ایمیل قبلا ثبت شده است',
|
||||
},
|
||||
EMAIL_ALREADY_IN_USE: {
|
||||
status: HttpStatus.CONFLICT,
|
||||
message: 'Email already in use',
|
||||
messageFa: 'این ایمیل قبلا استفاده شده است',
|
||||
},
|
||||
PASSWORD_TOO_SHORT: {
|
||||
status: HttpStatus.CONFLICT,
|
||||
message: 'Password must be at least 8 characters',
|
||||
messageFa: 'رمز عبور باید حداقل ۸ کاراکتر باشد',
|
||||
},
|
||||
CANNOT_BLOCK_SELF: {
|
||||
status: HttpStatus.BAD_REQUEST,
|
||||
message: 'Cannot block your own account',
|
||||
messageFa: 'امکان مسدود کردن حساب کاربری خودتان وجود ندارد',
|
||||
},
|
||||
RATE_LIMIT_EXCEEDED: {
|
||||
status: HttpStatus.TOO_MANY_REQUESTS,
|
||||
message: 'User rate limit exceeded',
|
||||
messageFa: 'تعداد درخواستهای مجاز کاربر به پایان رسیده است',
|
||||
},
|
||||
SHAHKAR_NO_MATCH: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'No match found between the provided national code and mobile number',
|
||||
messageFa: 'تطبیقی بین کد ملی و شماره موبایل وارد شده یافت نشد',
|
||||
},
|
||||
CAR_POLICY_NOT_FOUND: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'No policy record found',
|
||||
messageFa: 'سوابق بیمهنامه خودرو یافت نشد',
|
||||
},
|
||||
REAL_ESTATE_NOT_FOUND: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'No property ownership found for the provided national code and postal code',
|
||||
messageFa: 'ملکی برای کد ملی و کد پستی وارد شده یافت نشد',
|
||||
},
|
||||
REQUEST_FAILED: {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: 'Request failed',
|
||||
messageFa: 'درخواست ناموفق بود',
|
||||
},
|
||||
} as const satisfies Record<string, ErrorCatalogEntry>;
|
||||
|
||||
export type AppErrorCode = keyof typeof ERROR_CATALOG;
|
||||
|
||||
export function isAppErrorCode(code: string): code is AppErrorCode {
|
||||
return code in ERROR_CATALOG;
|
||||
}
|
||||
|
||||
export function getErrorStatus(code: AppErrorCode): HttpStatus {
|
||||
return ERROR_CATALOG[code].status;
|
||||
}
|
||||
|
||||
export function buildNormalizedError(
|
||||
code: AppErrorCode,
|
||||
overrides: Partial<Omit<NormalizedErrorDto, 'code'>> = {},
|
||||
): NormalizedErrorDto {
|
||||
const entry = ERROR_CATALOG[code];
|
||||
return {
|
||||
code,
|
||||
message: overrides.message ?? entry.message,
|
||||
messageFa: overrides.messageFa ?? entry.messageFa,
|
||||
providerMessage: overrides.providerMessage,
|
||||
providerCode: overrides.providerCode,
|
||||
providerTrackingCode: overrides.providerTrackingCode,
|
||||
details: overrides.details,
|
||||
conflict: overrides.conflict,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a Persian error message for a given code.
|
||||
*
|
||||
* @param code The NormalizedErrorDto.code value
|
||||
* @param params Optional interpolation params (e.g. { provider, inquiryType })
|
||||
* @returns The Persian message or undefined when no translation exists
|
||||
*/
|
||||
export function resolveErrorMessageFa(
|
||||
code: string,
|
||||
params?: Record<string, string>,
|
||||
): string | undefined {
|
||||
const entry = ERROR_CATALOG[code as AppErrorCode];
|
||||
|
||||
if (!entry) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
void params;
|
||||
|
||||
return entry.messageFa;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map well-known provider error messages / codes that originate
|
||||
* from upstream providers (returned as providerMessage) to their
|
||||
* Persian equivalents when the provider itself does not return a
|
||||
* Persian message.
|
||||
*/
|
||||
export const PROVIDER_MESSAGE_TRANSLATIONS: Record<string, string> = {
|
||||
'No match found between the provided national code and mobile number':
|
||||
'تطبیقی بین کد ملی و شماره موبایل وارد شده یافت نشد',
|
||||
'Shahkar inquiry failed': 'خطا در استعلام شاهکار',
|
||||
'No policy record found': 'سوابق بیمهنامه خودرو یافت نشد',
|
||||
'Record not found': 'رکوردی یافت نشد',
|
||||
'Request failed': 'درخواست ناموفق بود',
|
||||
'No property ownership found for the provided national code and postal code':
|
||||
'ملکی برای کد ملی و کد پستی وارد شده یافت نشد',
|
||||
'Inquiry returned no matching result': 'نتیجهای مطابق با اطلاعات وارد شده یافت نشد',
|
||||
'Insufficient role permissions': 'سطح دسترسی کافی نیست',
|
||||
'Invalid credentials': 'نام کاربری یا رمز عبور صحیح نیست',
|
||||
'Account is inactive': 'حساب کاربری غیرفعال است',
|
||||
'Account is blocked': 'حساب کاربری مسدود شده است',
|
||||
'Invalid refresh token': 'توکن نوسازی نامعتبر است',
|
||||
};
|
||||
|
||||
export const PROVIDER_PUBLIC_MESSAGE_TRANSLATIONS: Record<
|
||||
string,
|
||||
{ message: string; messageFa: string }
|
||||
> = {
|
||||
'کد ملی اشتباه است': {
|
||||
message: 'Invalid national code',
|
||||
messageFa: 'کد ملی اشتباه است',
|
||||
},
|
||||
'کدملی اشتباه است': {
|
||||
message: 'Invalid national code',
|
||||
messageFa: 'کد ملی اشتباه است',
|
||||
},
|
||||
};
|
||||
|
||||
export const MESSAGE_CODE_MAP: Record<string, AppErrorCode> = {
|
||||
'Invalid credentials': 'INVALID_CREDENTIALS',
|
||||
'Account is inactive': 'ACCOUNT_INACTIVE',
|
||||
'Account is blocked': 'ACCOUNT_BLOCKED',
|
||||
'Invalid refresh token': 'INVALID_REFRESH_TOKEN',
|
||||
'API key authentication is not configured': 'API_KEY_NOT_CONFIGURED',
|
||||
'Invalid or missing API key': 'INVALID_API_KEY',
|
||||
Unauthorized: 'UNAUTHORIZED',
|
||||
'Authentication required': 'AUTHENTICATION_REQUIRED',
|
||||
'Insufficient role permissions': 'INSUFFICIENT_ROLE',
|
||||
'Insufficient permissions to manage users': 'INSUFFICIENT_USER_MANAGEMENT_PERMISSION',
|
||||
'Only SUPER_ADMIN can assign SUPER_ADMIN role': 'SUPER_ADMIN_ROLE_REQUIRED',
|
||||
'User not found': 'USER_NOT_FOUND',
|
||||
'Username or email already exists': 'USERNAME_OR_EMAIL_EXISTS',
|
||||
'Email already in use': 'EMAIL_ALREADY_IN_USE',
|
||||
'Password must be at least 8 characters': 'PASSWORD_TOO_SHORT',
|
||||
'Cannot block your own account': 'CANNOT_BLOCK_SELF',
|
||||
'User rate limit exceeded': 'RATE_LIMIT_EXCEEDED',
|
||||
};
|
||||
|
||||
export function resolveErrorCodeFromMessage(message: string): AppErrorCode | undefined {
|
||||
return MESSAGE_CODE_MAP[message.trim()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to translate an upstream provider message to Persian.
|
||||
*
|
||||
* @param providerMessage The English message returned by the provider
|
||||
* @returns The Persian equivalent or undefined when no mapping exists
|
||||
*/
|
||||
export function translateProviderMessage(providerMessage: string): string | undefined {
|
||||
return PROVIDER_MESSAGE_TRANSLATIONS[providerMessage.trim()];
|
||||
}
|
||||
|
||||
export function resolveProviderPublicMessage(
|
||||
providerMessage: string | undefined,
|
||||
fallbackMessage = 'Provider request failed',
|
||||
): { message: string; messageFa: string } {
|
||||
const trimmed = providerMessage?.trim();
|
||||
if (!trimmed) {
|
||||
return {
|
||||
message: fallbackMessage,
|
||||
messageFa: ERROR_CATALOG.PROVIDER_ERROR.messageFa,
|
||||
};
|
||||
}
|
||||
|
||||
const direct = PROVIDER_PUBLIC_MESSAGE_TRANSLATIONS[trimmed];
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const messageFa = translateProviderMessage(trimmed);
|
||||
if (messageFa) {
|
||||
return {
|
||||
message: trimmed,
|
||||
messageFa,
|
||||
};
|
||||
}
|
||||
|
||||
if (/[آ-ی]/.test(trimmed)) {
|
||||
return {
|
||||
message: fallbackMessage,
|
||||
messageFa: trimmed,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
message: trimmed,
|
||||
messageFa: ERROR_CATALOG.PROVIDER_ERROR.messageFa,
|
||||
};
|
||||
}
|
||||
@@ -18,6 +18,9 @@ export class BaseInquiryResponseDto<T = Record<string, unknown>> {
|
||||
@ApiPropertyOptional({ example: 'Inquiry completed successfully' })
|
||||
message?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'استعلام با موفقیت انجام شد' })
|
||||
messageFa?: string;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
data?: T | null;
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ export class NormalizedErrorDto {
|
||||
@ApiProperty({ example: 'Provider request timed out' })
|
||||
message!: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'درخواست به سرویسدهنده زمانبر شد' })
|
||||
messageFa?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'سرویس در دسترس نیست' })
|
||||
providerMessage?: string;
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { AppException } from './app-exception';
|
||||
import {
|
||||
buildNormalizedError,
|
||||
resolveProviderPublicMessage,
|
||||
resolveErrorCodeFromMessage,
|
||||
} from '../constants/error-messages';
|
||||
import { translateError } from '../helpers/translate-error.helper';
|
||||
|
||||
describe('application error contract', () => {
|
||||
it('builds normalized errors from stable catalog codes', () => {
|
||||
const error = buildNormalizedError('INVALID_CREDENTIALS');
|
||||
|
||||
expect(error).toEqual({
|
||||
code: 'INVALID_CREDENTIALS',
|
||||
message: 'Invalid credentials',
|
||||
messageFa: 'نام کاربری یا رمز عبور صحیح نیست',
|
||||
providerMessage: undefined,
|
||||
providerCode: undefined,
|
||||
providerTrackingCode: undefined,
|
||||
details: undefined,
|
||||
conflict: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('serializes AppException with the catalog status and normalized error', () => {
|
||||
const exception = new AppException('RATE_LIMIT_EXCEEDED');
|
||||
|
||||
expect(exception.getStatus()).toBe(HttpStatus.TOO_MANY_REQUESTS);
|
||||
expect(exception.normalizedError.code).toBe('RATE_LIMIT_EXCEEDED');
|
||||
expect(exception.normalizedError.messageFa).toBe(
|
||||
'تعداد درخواستهای مجاز کاربر به پایان رسیده است',
|
||||
);
|
||||
});
|
||||
|
||||
it('bridges known legacy English messages to catalog codes', () => {
|
||||
expect(resolveErrorCodeFromMessage('Invalid credentials')).toBe('INVALID_CREDENTIALS');
|
||||
expect(
|
||||
translateError({
|
||||
code: 'HTTP_ERROR',
|
||||
message: 'Invalid credentials',
|
||||
}),
|
||||
).toMatchObject({
|
||||
code: 'INVALID_CREDENTIALS',
|
||||
messageFa: 'نام کاربری یا رمز عبور صحیح نیست',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps raw provider diagnostics separate from public provider messages', () => {
|
||||
expect(
|
||||
translateError({
|
||||
code: 'PROVIDER_ERROR',
|
||||
message: 'Invalid national code',
|
||||
messageFa: 'کد ملی اشتباه است',
|
||||
providerMessage: 'کد ملی اشتباه است',
|
||||
providerCode: 'PROVIDER_ERROR',
|
||||
providerTrackingCode: 'provider-tracking',
|
||||
}),
|
||||
).toEqual({
|
||||
code: 'PROVIDER_ERROR',
|
||||
message: 'Invalid national code',
|
||||
messageFa: 'کد ملی اشتباه است',
|
||||
providerMessage: 'کد ملی اشتباه است',
|
||||
providerCode: 'PROVIDER_ERROR',
|
||||
providerTrackingCode: 'provider-tracking',
|
||||
details: undefined,
|
||||
conflict: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('maps known Persian provider text to stable public English and Persian messages', () => {
|
||||
expect(resolveProviderPublicMessage('کد ملی اشتباه است')).toEqual({
|
||||
message: 'Invalid national code',
|
||||
messageFa: 'کد ملی اشتباه است',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the generic public message for unknown provider errors', () => {
|
||||
expect(
|
||||
translateError({
|
||||
code: 'UNKNOWN_ERROR',
|
||||
message: 'Unknown provider error',
|
||||
providerMessage: 'No policy record found',
|
||||
providerCode: 'POLICY_NOT_FOUND',
|
||||
}),
|
||||
).toMatchObject({
|
||||
code: 'UNKNOWN_ERROR',
|
||||
message: 'Unknown provider error',
|
||||
messageFa: 'خطای ناشناخته در سرویسدهنده',
|
||||
providerMessage: 'No policy record found',
|
||||
providerCode: 'POLICY_NOT_FOUND',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
|
||||
import {
|
||||
AppErrorCode,
|
||||
buildNormalizedError,
|
||||
getErrorStatus,
|
||||
} from '../constants/error-messages';
|
||||
|
||||
export interface AppExceptionOptions {
|
||||
message?: string;
|
||||
messageFa?: string;
|
||||
providerMessage?: string;
|
||||
providerCode?: string;
|
||||
providerTrackingCode?: string;
|
||||
details?: NormalizedErrorDto['details'];
|
||||
conflict?: NormalizedErrorDto['conflict'];
|
||||
status?: HttpStatus;
|
||||
}
|
||||
|
||||
export class AppException extends HttpException {
|
||||
public readonly normalizedError: NormalizedErrorDto;
|
||||
|
||||
constructor(code: AppErrorCode, options: AppExceptionOptions = {}) {
|
||||
const normalizedError = buildNormalizedError(code, options);
|
||||
super(
|
||||
{
|
||||
message: normalizedError.message,
|
||||
error: normalizedError,
|
||||
},
|
||||
options.status ?? getErrorStatus(code),
|
||||
);
|
||||
this.normalizedError = normalizedError;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,12 @@ import { NormalizedErrorDto } from '../dto/normalized-error.dto';
|
||||
import { buildInquiryResponse } from '../helpers/inquiry-response.helper';
|
||||
import { ProviderException } from '../exceptions/provider.exception';
|
||||
import { isNormalizedError } from '../helpers/validation-error.helper';
|
||||
import { translateError } from '../helpers/translate-error.helper';
|
||||
import { AppException } from '../exceptions/app-exception';
|
||||
import {
|
||||
buildNormalizedError,
|
||||
resolveErrorCodeFromMessage,
|
||||
} from '../constants/error-messages';
|
||||
|
||||
/**
|
||||
* Global exception filter — normalizes all errors into BaseInquiryResponseDto
|
||||
@@ -52,20 +58,24 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
}
|
||||
|
||||
private extractNormalizedError(exception: unknown): NormalizedErrorDto {
|
||||
if (exception instanceof ProviderException) {
|
||||
if (exception instanceof AppException) {
|
||||
return exception.normalizedError;
|
||||
}
|
||||
|
||||
if (exception instanceof ProviderException) {
|
||||
return translateError(exception.normalizedError);
|
||||
}
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
const res = exception.getResponse();
|
||||
|
||||
if (typeof res === 'object' && res !== null) {
|
||||
if ('error' in res && isNormalizedError((res as { error: unknown }).error)) {
|
||||
return (res as { error: NormalizedErrorDto }).error;
|
||||
return translateError((res as { error: NormalizedErrorDto }).error);
|
||||
}
|
||||
|
||||
if (isNormalizedError(res)) {
|
||||
return res;
|
||||
return translateError(res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,15 +84,22 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
? res
|
||||
: (res as { message?: string | string[] }).message;
|
||||
|
||||
return {
|
||||
code: 'HTTP_ERROR',
|
||||
message: Array.isArray(message) ? message.join(', ') : String(message ?? exception.message),
|
||||
};
|
||||
const normalizedMessage = Array.isArray(message)
|
||||
? message.join(', ')
|
||||
: String(message ?? exception.message);
|
||||
const code = resolveErrorCodeFromMessage(normalizedMessage);
|
||||
|
||||
return code
|
||||
? buildNormalizedError(code, { message: normalizedMessage })
|
||||
: translateError({
|
||||
code: 'HTTP_ERROR',
|
||||
message: normalizedMessage,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
return translateError({
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: exception instanceof Error ? exception.message : 'Unexpected error',
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BaseInquiryResponseDto } from '../dto/base-inquiry-response.dto';
|
||||
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
|
||||
import { translateError } from './translate-error.helper';
|
||||
|
||||
export function buildInquiryResponse<T = Record<string, unknown>>(params: {
|
||||
success: boolean;
|
||||
@@ -10,14 +11,17 @@ export function buildInquiryResponse<T = Record<string, unknown>>(params: {
|
||||
data?: T | null;
|
||||
error?: NormalizedErrorDto | null;
|
||||
}): BaseInquiryResponseDto<T> {
|
||||
const error = params.success ? null : (params.error != null ? translateError(params.error) : null);
|
||||
|
||||
return {
|
||||
success: params.success,
|
||||
provider: params.provider,
|
||||
trackingCode: params.trackingCode,
|
||||
message: params.message,
|
||||
message: params.success ? params.message : undefined,
|
||||
messageFa: undefined,
|
||||
duration: params.duration,
|
||||
data: params.success ? (params.data ?? null) : null,
|
||||
error: params.success ? null : (params.error ?? null),
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
|
||||
import {
|
||||
buildNormalizedError,
|
||||
isAppErrorCode,
|
||||
resolveErrorMessageFa,
|
||||
resolveErrorCodeFromMessage,
|
||||
} from '../constants/error-messages';
|
||||
|
||||
/**
|
||||
* Ensures a NormalizedErrorDto has its `messageFa` field populated.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. If `messageFa` is already set, return as-is.
|
||||
* 2. If a broad gateway error carries a known legacy message, map it to that catalog code.
|
||||
* 3. Use the gateway-owned code-based translation map.
|
||||
* 4. If nothing matches, return unchanged.
|
||||
*/
|
||||
export function translateError(error: NormalizedErrorDto): NormalizedErrorDto {
|
||||
if (error.messageFa) {
|
||||
return error;
|
||||
}
|
||||
|
||||
// Build interpolation context from the error
|
||||
const params: Record<string, string> = {};
|
||||
if (error.providerCode) params.providerCode = error.providerCode;
|
||||
if (error.providerTrackingCode) params.providerTrackingCode = error.providerTrackingCode;
|
||||
|
||||
if (isAppErrorCode(error.code)) {
|
||||
if (error.code === 'HTTP_ERROR' || error.code === 'INTERNAL_ERROR') {
|
||||
const messageCode = resolveErrorCodeFromMessage(error.message);
|
||||
if (messageCode) {
|
||||
return buildNormalizedError(messageCode, {
|
||||
message: error.message,
|
||||
messageFa: error.messageFa,
|
||||
providerMessage: error.providerMessage,
|
||||
providerCode: error.providerCode,
|
||||
providerTrackingCode: error.providerTrackingCode,
|
||||
details: error.details,
|
||||
conflict: error.conflict,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return buildNormalizedError(error.code, {
|
||||
message: error.message,
|
||||
messageFa: error.messageFa,
|
||||
providerMessage: error.providerMessage,
|
||||
providerCode: error.providerCode,
|
||||
providerTrackingCode: error.providerTrackingCode,
|
||||
details: error.details,
|
||||
conflict: error.conflict,
|
||||
});
|
||||
}
|
||||
|
||||
const messageFa = resolveErrorMessageFa(error.code, params);
|
||||
if (messageFa) return { ...error, messageFa };
|
||||
|
||||
// Last resort: return unchanged
|
||||
return error;
|
||||
}
|
||||
@@ -1,11 +1,126 @@
|
||||
import { ValidationError } from 'class-validator';
|
||||
import { NormalizedErrorDto } from '../dto/normalized-error.dto';
|
||||
import { buildNormalizedError } from '../constants/error-messages';
|
||||
|
||||
export interface ValidationFieldError {
|
||||
field: string;
|
||||
constraints: string[];
|
||||
}
|
||||
|
||||
const FIELD_LABELS_FA: Record<string, string> = {
|
||||
nationalCode: 'کد ملی',
|
||||
postalCode: 'کد پستی',
|
||||
birthDate: 'تاریخ تولد',
|
||||
mobileNo: 'شماره موبایل',
|
||||
sheba: 'شماره شبا',
|
||||
chassisNo: 'شماره شاسی',
|
||||
plk1: 'بخش اول پلاک',
|
||||
plk2: 'حرف پلاک',
|
||||
plk3: 'بخش سوم پلاک',
|
||||
plksrl: 'سری پلاک',
|
||||
email: 'ایمیل',
|
||||
password: 'رمز عبور',
|
||||
newPassword: 'رمز عبور جدید',
|
||||
role: 'نقش کاربر',
|
||||
clientType: 'نوع کاربر',
|
||||
username: 'نام کاربری',
|
||||
fullName: 'نام کامل',
|
||||
};
|
||||
|
||||
const CONSTRAINT_PRIORITY = [
|
||||
'isNotEmpty',
|
||||
'matches',
|
||||
'isLength',
|
||||
'length',
|
||||
'minLength',
|
||||
'maxLength',
|
||||
'isEmail',
|
||||
'isEnum',
|
||||
'isIn',
|
||||
'isString',
|
||||
'isInt',
|
||||
'isBoolean',
|
||||
'isArray',
|
||||
];
|
||||
|
||||
function pickConstraint(constraints: Record<string, string>): string {
|
||||
for (const key of CONSTRAINT_PRIORITY) {
|
||||
if (constraints[key]) {
|
||||
return constraints[key];
|
||||
}
|
||||
}
|
||||
|
||||
return Object.values(constraints)[0] ?? 'Invalid value';
|
||||
}
|
||||
|
||||
function fieldLabelFa(field: string): string {
|
||||
return FIELD_LABELS_FA[field] ?? field;
|
||||
}
|
||||
|
||||
function translateValidationConstraint(field: string, constraint: string): string {
|
||||
const label = fieldLabelFa(field);
|
||||
|
||||
if (constraint.includes('must be exactly 10 digits')) {
|
||||
return `${label} باید دقیقا ۱۰ رقم باشد`;
|
||||
}
|
||||
|
||||
if (constraint.includes('birthDate must be in YYYY-MM-DD format')) {
|
||||
return 'تاریخ تولد باید با فرمت YYYY-MM-DD باشد';
|
||||
}
|
||||
|
||||
if (constraint.includes('birthDate must be in YYYY-MM-DD or YYYYMMDD format')) {
|
||||
return 'تاریخ تولد باید با فرمت YYYY-MM-DD یا YYYYMMDD باشد';
|
||||
}
|
||||
|
||||
if (constraint.includes('mobileNo must be an Iranian mobile number')) {
|
||||
return 'شماره موبایل باید معتبر و با 09 شروع شود';
|
||||
}
|
||||
|
||||
if (constraint.includes('sheba must start with IR and contain 24 digits')) {
|
||||
return 'شماره شبا باید با IR شروع شود و ۲۴ رقم داشته باشد';
|
||||
}
|
||||
|
||||
const exactDigits = constraint.match(/must be exactly (\d+) digits/);
|
||||
if (exactDigits?.[1]) {
|
||||
return `${label} باید دقیقا ${exactDigits[1]} رقم باشد`;
|
||||
}
|
||||
|
||||
const minLength = constraint.match(/must be longer than or equal to (\d+) characters/);
|
||||
if (minLength?.[1]) {
|
||||
return `${label} باید حداقل ${minLength[1]} کاراکتر باشد`;
|
||||
}
|
||||
|
||||
if (constraint.includes('must be an email')) {
|
||||
return 'ایمیل باید معتبر باشد';
|
||||
}
|
||||
|
||||
if (constraint.includes('must be one of the following values')) {
|
||||
return `${label} مقدار معتبری ندارد`;
|
||||
}
|
||||
|
||||
if (constraint.includes('should not be empty')) {
|
||||
return `${label} الزامی است`;
|
||||
}
|
||||
|
||||
if (constraint.includes('must be a string')) {
|
||||
return `${label} باید متن باشد`;
|
||||
}
|
||||
|
||||
if (constraint.includes('must be an integer number')) {
|
||||
return `${label} باید عدد صحیح باشد`;
|
||||
}
|
||||
|
||||
if (constraint.includes('must be a boolean value')) {
|
||||
return `${label} باید مقدار درست یا نادرست باشد`;
|
||||
}
|
||||
|
||||
if (constraint.includes('must be an array')) {
|
||||
return `${label} باید آرایه باشد`;
|
||||
}
|
||||
|
||||
return `${label} معتبر نیست`;
|
||||
}
|
||||
|
||||
export function flattenValidationErrors(
|
||||
errors: ValidationError[],
|
||||
parentPath = '',
|
||||
@@ -18,7 +133,7 @@ export function flattenValidationErrors(
|
||||
if (error.constraints) {
|
||||
result.push({
|
||||
field,
|
||||
constraints: Object.values(error.constraints),
|
||||
constraints: [pickConstraint(error.constraints)],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,18 +149,19 @@ 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';
|
||||
const details = flattenValidationErrors(errors).slice(0, 1);
|
||||
const selected = details[0];
|
||||
const summary = selected?.constraints[0] ?? 'Request validation failed';
|
||||
const messageFa = selected
|
||||
? translateValidationConstraint(selected.field, selected.constraints[0] ?? '')
|
||||
: 'اطلاعات ورودی نامعتبر است';
|
||||
|
||||
return {
|
||||
normalizedError: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
normalizedError: buildNormalizedError('VALIDATION_ERROR', {
|
||||
message: summary,
|
||||
messageFa,
|
||||
details,
|
||||
},
|
||||
}),
|
||||
details,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user