-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.ts
More file actions
75 lines (65 loc) · 2.11 KB
/
errors.ts
File metadata and controls
75 lines (65 loc) · 2.11 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
import type { SkillError, SkillResponse } from './types.js';
export class HttpStatusError extends Error {
public readonly status: number;
public readonly body: unknown;
public readonly code: string;
constructor(status: number, body: unknown, code = 'HTTP_ERROR') {
super(`HTTP request failed with status ${status}`);
this.name = 'HttpStatusError';
this.status = status;
this.body = body;
this.code = code;
}
}
function stringifyRaw(input: unknown): string {
if (input == null) {
return '';
}
if (typeof input === 'string') {
return input;
}
try {
return JSON.stringify(input);
} catch {
return String(input);
}
}
export function normalizeError(input: unknown, fallbackCode = 'UNKNOWN_ERROR'): SkillError {
if (input instanceof HttpStatusError) {
const body = input.body as Record<string, unknown> | undefined;
const error = body?.Error as Record<string, unknown> | undefined;
return {
code: String(error?.Code || input.code || fallbackCode),
message: String(error?.Message || input.message || 'HTTP request failed'),
details: String(error?.Details || ''),
httpStatus: input.status,
raw: input.body,
};
}
if (input instanceof Error) {
const maybeCode =
typeof (input as { code?: unknown }).code === 'string'
? String((input as { code?: unknown }).code)
: '';
const maybeDetails = (input as { details?: unknown }).details;
const maybeRaw = (input as { raw?: unknown }).raw;
return {
code: maybeCode || fallbackCode,
message: input.message,
details: maybeDetails !== undefined ? stringifyRaw(maybeDetails) : '',
raw: maybeRaw !== undefined ? maybeRaw : { name: input.name, stack: input.stack },
};
}
return {
code: fallbackCode,
message: 'Unhandled error',
details: stringifyRaw(input),
raw: input,
};
}
export function okResponse<T>(traceId: string, data: T): SkillResponse<T> {
return { ok: true, data, traceId };
}
export function errorResponse<T>(traceId: string, error: SkillError): SkillResponse<T> {
return { ok: false, error, traceId };
}