H
Hono2mo ago
Danko

HTTP Status bug

Getting a weird bug when returning a response in my project for a post request. Previous get requests return data correctly, but this one is giving me problems for some obscure reason. This results in an Internal server error Error message: The status provided (0) must be 101 or in the range of [200, 599]
13 Replies
Danko
DankoOP2mo ago
Route handler:
.post(
"/bid",
zValidator("json", z.object({ amount: z.number().optional() })),
async (c) => {
const userId = c.var.user.id;
const auctionId = c.var.auction.id;

const { amount } = c.req.valid("json");

console.log("newAmount", amount);

if (amount) {
return c.json(
{ error: "Amount is required for placing a bid." },
HttpStatusCode.OK_200
);
}

const updatedAuction = await auctionService.placeBid(
auctionId,
userId,
amount
);

return c.json({ data: updatedAuction }, HttpStatusCode.OK_200);
}
)
.post(
"/bid",
zValidator("json", z.object({ amount: z.number().optional() })),
async (c) => {
const userId = c.var.user.id;
const auctionId = c.var.auction.id;

const { amount } = c.req.valid("json");

console.log("newAmount", amount);

if (amount) {
return c.json(
{ error: "Amount is required for placing a bid." },
HttpStatusCode.OK_200
);
}

const updatedAuction = await auctionService.placeBid(
auctionId,
userId,
amount
);

return c.json({ data: updatedAuction }, HttpStatusCode.OK_200);
}
)
I added the early return JSON for testing purposes, but the same result occurs
ambergristle
ambergristle2mo ago
what is the value of HttpStatusCode.OK_200?
Danko
DankoOP2mo ago
200 replaced with an enum to not use magic numbers I will send a middleware that is also used, but no status is being set
ambergristle
ambergristle2mo ago
magic numbers? http status codes definitely aren't magic numbers the error message is telling you that Bun is getting 0 instead of 200 for the status, so i'd start by replacing the enums with integers, at least to debug hono only lets you use valid status codes with the response helpers (like c.json), so it's totally type-safe
Danko
DankoOP2mo ago
It's a lint rule I have set up for my code base, yeah status codes are protocol level so everyone should know them, but for juniors that might be looking at the codebase that might not be the case
<-- POST /api/auction/onoonrye7pr5914vbfmq9dk9/bid
57 | headers: this.#preparedHeaders ??= new Headers()
58 | });
59 | }
60 | set res(_res) {
61 | if (this.#res && _res) {
62 | _res = new Response(_res.body, _res);
^
RangeError: The status provided (0) must be 101 or in the range of [200, 599]
at Response (/Users/dankokrupljanin/projects/side-projects/car-auction-api/node_modules/hono/dist/context.js:62:18)

newAmount 43148
entering if statement
--> POST /api/auction/onoonrye7pr5914vbfmq9dk9/bid 500 15ms
<-- POST /api/auction/onoonrye7pr5914vbfmq9dk9/bid
57 | headers: this.#preparedHeaders ??= new Headers()
58 | });
59 | }
60 | set res(_res) {
61 | if (this.#res && _res) {
62 | _res = new Response(_res.body, _res);
^
RangeError: The status provided (0) must be 101 or in the range of [200, 599]
at Response (/Users/dankokrupljanin/projects/side-projects/car-auction-api/node_modules/hono/dist/context.js:62:18)

newAmount 43148
entering if statement
--> POST /api/auction/onoonrye7pr5914vbfmq9dk9/bid 500 15ms
// tsconfig.json
{
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"types": ["bun-types"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx",
"resolveJsonModule": true,
"noUnusedParameters": false,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,

"baseUrl": "src",
"paths": {
"@/*": ["*"]
}
}
}
// tsconfig.json
{
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node",
"types": ["bun-types"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx",
"resolveJsonModule": true,
"noUnusedParameters": false,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,

"baseUrl": "src",
"paths": {
"@/*": ["*"]
}
}
}
this is a middleware that I'm using before the request
const provideAuction = (urlParam = "auctionId") =>
createMiddleware<HonoVariables<WithAuctionVariables>>(async (c, next) => {
const id = c.req.param(urlParam);
const userId = c.var.user.id;

if (!userId) {
throw new Error(
"Invalid implementation, `provideAuction` middleware relies on protectedMiddleware"
);
}

if (!id) {
throw new Error(
"Invalid implementation, check if the url param is correct"
);
}

const data = await auctionService.getById(id);

if (!data) {
throw new HTTPException(404, { message: "Auction not found" });
}

c.set("auction", data);

next();
});
const provideAuction = (urlParam = "auctionId") =>
createMiddleware<HonoVariables<WithAuctionVariables>>(async (c, next) => {
const id = c.req.param(urlParam);
const userId = c.var.user.id;

if (!userId) {
throw new Error(
"Invalid implementation, `provideAuction` middleware relies on protectedMiddleware"
);
}

if (!id) {
throw new Error(
"Invalid implementation, check if the url param is correct"
);
}

const data = await auctionService.getById(id);

if (!data) {
throw new HTTPException(404, { message: "Auction not found" });
}

c.set("auction", data);

next();
});
I'm running hono@^4.8.5, the zod validator shouldn't be the problem as the request enters the if statement reverted my tsconfig to something simpler, but no improvements
{
"compilerOptions": {
"strict": true,
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx",
"baseUrl": "src",
"paths": {
"@/*": ["*"]
}
}
}
{
"compilerOptions": {
"strict": true,
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx",
"baseUrl": "src",
"paths": {
"@/*": ["*"]
}
}
}
Danko
DankoOP2mo ago
No description
ambergristle
ambergristle2mo ago
it's a runtime error, not a typescript issue try replacing the status code enums with integer values
Danko
DankoOP2mo ago
I know, thought maybe the bunde/module affected honos esm/module imports, but that likely isnt the case as it's bundled code
ambergristle
ambergristle2mo ago
unless you're overriding the status code somewhere else, the enums seem like they could be the issue
Danko
DankoOP2mo ago
this is the code that ran for the screenshot
No description
Danko
DankoOP2mo ago
I introduced the enum after the bug started occurring as I thought I was crazy the get requests in the router with the same 200 number where doing OK, but the post request wasn't the exception is occurring before my console.logs ok I figured it out the provideAuction middleware didn't return the next() result sorry @ambergristle for the hassle
ambergristle
ambergristle2mo ago
no worries; happy to help!
Danko
DankoOP2mo ago
how do I mark this as solved now? found it

Did you find this page helpful?