forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-75-Lilly-Protocol-lily-frontend.ts
More file actions
87 lines (76 loc) · 2.09 KB
/
Copy pathgithub-75-Lilly-Protocol-lily-frontend.ts
File metadata and controls
87 lines (76 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// src/types/error.ts
export interface ApiErrorDetails {
field?: string;
value?: unknown;
constraints?: Record<string, string>;
[key: string]: unknown;
}
export interface ApiError {
code: string;
message: string;
details?: ApiErrorDetails[];
timestamp: string;
path?: string;
method?: string;
}
export interface ErrorResponse {
error?: ApiError;
errors?: ApiErrorDetails[];
message?: string;
timestamp?: string;
path?: string;
method?: string;
[key: string]: unknown;
}
// src/utils/error.ts
import { ApiError, ErrorResponse } from '@/types/error';
export function isApiError(error: unknown): error is ApiError {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
'message' in error
);
}
export function normalizeApiError(error: ErrorResponse | string): ApiError {
if (typeof error === 'string') {
return {
code: 'UNKNOWN_ERROR',
message: error,
timestamp: new Date().toISOString(),
};
}
if (isApiError(error)) {
return {
code: error.code,
message: error.message,
details: error.details,
timestamp: error.timestamp || new Date().toISOString(),
path: error.path,
method: error.method,
};
}
// Handle common error response formats
const message = error.message || (error.error?.message ?? 'An unknown error occurred');
const code = error.error?.code || (error.errors?.[0]?.constraints?.[Object.keys(error.errors?.[0]?.constraints || {})[0]] ?? 'API_ERROR');
return {
code: typeof code === 'string' ? code : 'API_ERROR',
message,
details: error.errors,
timestamp: error.timestamp || new Date().toISOString(),
path: error.path,
method: error.method,
};
}
export function formatApiError(error: ApiError): string {
if (error.details && error.details.length > 0) {
const fieldErrors = error.details
.filter(d => d.field)
.map(d => `${d.field}: ${Object.values(d.constraints || {}).join(', ')}`)
.join('; ');
if (fieldErrors) {
return `${error.message} (${fieldErrors})`;
}
}
return error.message;
}