improvement: error handeling structure changed and unified all across the app. user no longer sees inappropriate messages.
This commit is contained in:
@@ -1,5 +1,66 @@
|
||||
export interface ApiErrorDetail {
|
||||
field: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
statusCode: number;
|
||||
message: string | string[];
|
||||
error?: string;
|
||||
code: string;
|
||||
details?: ApiErrorDetail[];
|
||||
}
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
success: false;
|
||||
error: {
|
||||
code: string;
|
||||
statusCode: number;
|
||||
details?: ApiErrorDetail[];
|
||||
};
|
||||
}
|
||||
|
||||
export function isApiError(value: unknown): value is ApiError {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'code' in value &&
|
||||
typeof (value as ApiError).code === 'string' &&
|
||||
'statusCode' in value &&
|
||||
typeof (value as ApiError).statusCode === 'number'
|
||||
);
|
||||
}
|
||||
|
||||
export function asApiError(value: unknown): ApiError | null {
|
||||
if (isApiError(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'response' in value &&
|
||||
typeof (value as { response?: { data?: ApiErrorResponse } }).response?.data === 'object'
|
||||
) {
|
||||
const payload = (value as { response: { data?: ApiErrorResponse } }).response.data;
|
||||
if (payload?.success === false && payload.error?.code) {
|
||||
return {
|
||||
statusCode: payload.error.statusCode,
|
||||
code: payload.error.code,
|
||||
details: payload.error.details,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @deprecated Use ApiError.code — kept for transitional parsing only. */
|
||||
export function legacyStatusCode(value: unknown): number | undefined {
|
||||
if (isApiError(value)) {
|
||||
return value.statusCode;
|
||||
}
|
||||
if (typeof value === 'object' && value !== null && 'statusCode' in value) {
|
||||
const statusCode = (value as { statusCode?: unknown }).statusCode;
|
||||
return typeof statusCode === 'number' ? statusCode : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user