-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy patherrors.ts
More file actions
156 lines (146 loc) · 4.1 KB
/
errors.ts
File metadata and controls
156 lines (146 loc) · 4.1 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { NextApiResponse } from "next";
import { z } from "zod";
import { ApiError, ErrorCode } from "./types/api-error";
export const apiError = (
res: NextApiResponse,
status: number,
code: ErrorCode,
error: string,
details?: string
) => {
console.error(`[API Error] ${code}: ${error}`, details ?? "");
const response = { error, code, details } as ApiError;
res.status(status).json(response);
return response;
};
export const badRequest = (
res: NextApiResponse,
message: string,
details?: string
) => apiError(res, 400, "VALIDATION_ERROR", message, details);
export const notFound = (
res: NextApiResponse,
message: string,
details?: string
) => apiError(res, 404, "NOT_FOUND", message, details);
export const internalError = (res: NextApiResponse, err?: unknown) =>
apiError(
res,
500,
"INTERNAL_ERROR",
"Internal server error",
err instanceof Error ? err.message : undefined
);
export const externalApiError = (
res: NextApiResponse,
service: string,
details?: string
) =>
apiError(
res,
502,
"EXTERNAL_API_ERROR",
`Failed to fetch from ${service}`,
details
);
export const methodNotAllowed = (
res: NextApiResponse,
method: string,
allowed: string[]
) => {
res.setHeader("Allow", allowed);
return apiError(
res,
405,
"METHOD_NOT_ALLOWED",
`Method ${method} Not Allowed`
);
};
/**
* Validates input data against a Zod schema.
* Returns an error response if validation fails.
*
* @param inputResult - The result from Zod's safeParse()
* @param res - Next.js API response object
* @param errorMessage - Error message to return if validation fails (e.g., "Invalid address format")
* @returns The error response if validation failed, undefined otherwise
*/
export const validateInput = <T>(
inputResult:
| { success: true; data: T }
| { success: false; error: z.ZodError<T> },
res: NextApiResponse,
errorMessage: string
): NextApiResponse | undefined => {
if (!inputResult.success) {
badRequest(
res,
errorMessage,
inputResult.error.issues.map((e) => e.message).join(", ")
);
return res;
}
return undefined;
};
/**
* Validates output data against a Zod schema.
* In development, returns an error response if validation fails.
* In production, logs the error but allows execution to continue.
*
* @param outputResult - The result from Zod's safeParse()
* @param res - Next.js API response object
* @param endpointName - Name of the endpoint for logging (e.g., "api/account-balance")
* @returns The error response if validation failed in development, undefined otherwise
*/
export const validateOutput = <T>(
outputResult:
| { success: true; data: T }
| { success: false; error: z.ZodError<T> },
res: NextApiResponse,
endpointName: string
): NextApiResponse | undefined => {
if (!outputResult.success) {
console.error(
`[${endpointName}] Output validation failed:`,
outputResult.error
);
// In production, we might still return the data, but log the error
// In development, this helps catch contract/API changes early
if (process.env.NODE_ENV === "development") {
internalError(
res,
new Error(
`Output validation failed: ${outputResult.error.issues
.map((e) => e.message)
.join(", ")}`
)
);
return res;
}
}
return undefined;
};
/**
* Validates data from an external API against a Zod schema.
* Returns null if validation fails and logs the error.
*
* @param result - The result from Zod's safeParse()
* @param context - Context for logging (e.g. "api/regions")
* @param extraInfo - Additional info for logging (e.g. URL)
* @returns The validated data or null if validation failed
*/
export const validateExternalResponse = <T>(
result: { success: true; data: T } | { success: false; error: z.ZodError<T> },
context: string,
extraInfo?: string
): T | null => {
if (!result.success) {
console.error(
`[${context}] External API response validation failed:`,
result.error,
extraInfo || ""
);
return null;
}
return result.data;
};