Skip to content

Commit 95f6220

Browse files
committed
fix(middleware): return proper 400 response when failing to parse accept header
1 parent a9878ac commit 95f6220

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

src/middleware.ts

+31-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import contentTypeUtil from "content-type";
22
import { isHttpError } from "http-errors";
33
import type { Middleware, ParameterizedContext } from "koa";
4-
import { type JsonApiMediaType, getAcceptableMediaTypes } from "./accept.js";
4+
import { type JsonApiMediaType, ParserError, getAcceptableMediaTypes } from "./accept.js";
55
import { JsonApiBody, JsonApiErrorBody } from "./body.js";
66
import { InputValidationError } from "./request.js";
77

@@ -13,9 +13,36 @@ type JsonApiState = {
1313

1414
export const jsonApiRequestMiddleware = (): Middleware<JsonApiState> => {
1515
return async (context, next) => {
16-
context.state.jsonApi = {
17-
acceptableTypes: getAcceptableMediaTypes(context.get("Accept")),
18-
};
16+
try {
17+
context.state.jsonApi = {
18+
acceptableTypes: getAcceptableMediaTypes(context.get("Accept")),
19+
};
20+
} catch (error) {
21+
if (!(error instanceof ParserError)) {
22+
throw error;
23+
}
24+
25+
context.status = 400;
26+
context.set(
27+
"Content-Type",
28+
contentTypeUtil.format({ type: "application/vnd.api+json" }),
29+
);
30+
context.body = {
31+
jsonapi: { version: "1.1" },
32+
errors: [
33+
{
34+
status: "400",
35+
code: "bad_request",
36+
title: "Bad Request",
37+
detail: error.message,
38+
source: {
39+
header: "accept",
40+
},
41+
},
42+
],
43+
};
44+
return;
45+
}
1946

2047
await next();
2148
handleResponse(context);

0 commit comments

Comments
 (0)