icebear0828 commited on
Commit
0be9bdf
·
1 Parent(s): 38e103b

fix(api): return 400 invalid_json for malformed chat payload

Browse files
src/middleware/error-handler.ts CHANGED
@@ -48,6 +48,18 @@ export async function errorHandler(c: Context, next: Next): Promise<void> {
48
  const status = (err as { status?: number }).status;
49
  const path = c.req.path;
50
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  // Anthropic Messages API errors
52
  if (path.startsWith("/v1/messages")) {
53
  if (status === 401) {
 
48
  const status = (err as { status?: number }).status;
49
  const path = c.req.path;
50
 
51
+ // Malformed JSON request body should be treated as a client error.
52
+ if (err instanceof SyntaxError && message.toLowerCase().includes("json")) {
53
+ c.status(400);
54
+ return c.json(
55
+ makeOpenAIError(
56
+ "Malformed JSON request body",
57
+ "invalid_request_error",
58
+ "invalid_json",
59
+ ),
60
+ ) as never;
61
+ }
62
+
63
  // Anthropic Messages API errors
64
  if (path.startsWith("/v1/messages")) {
65
  if (status === 401) {
src/routes/chat.ts CHANGED
@@ -89,7 +89,21 @@ export function createChatRoutes(
89
  }
90
 
91
  // Parse request
92
- const body = await c.req.json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  const parsed = ChatCompletionRequestSchema.safeParse(body);
94
  if (!parsed.success) {
95
  c.status(400);
 
89
  }
90
 
91
  // Parse request
92
+ let body: unknown;
93
+ try {
94
+ body = await c.req.json();
95
+ } catch {
96
+ c.status(400);
97
+ return c.json({
98
+ error: {
99
+ message: "Malformed JSON request body",
100
+ type: "invalid_request_error",
101
+ param: null,
102
+ code: "invalid_json",
103
+ },
104
+ });
105
+ }
106
+
107
  const parsed = ChatCompletionRequestSchema.safeParse(body);
108
  if (!parsed.success) {
109
  c.status(400);