How to prevent Server Error if no req body?

Hi I have this code:
userRouter.patch("/self", async (c) => {
const reqUserId = c.get("authUser").user?.id;

if (reqUserId == null) {
throw new HTTPException(401);
}

const { name } = await c.req.json();

if (!name) {
throw new HTTPException(400, { message: "Please include a new name in body." });
}

return c.json({});
});
userRouter.patch("/self", async (c) => {
const reqUserId = c.get("authUser").user?.id;

if (reqUserId == null) {
throw new HTTPException(401);
}

const { name } = await c.req.json();

if (!name) {
throw new HTTPException(400, { message: "Please include a new name in body." });
}

return c.json({});
});
If no json is passed in the body i get this error: [ERROR] SyntaxError: Unexpected end of JSON input Is there anyway to replace this with my own error message? Like the one in my code ^ ?
4 Replies
gwapes
gwapes4w ago
Use try catch and then return if it throws.
Greenman999
Greenman999OP4w ago
ok thanks
Steven-sensei
Steven-sensei4w ago
try catch ?
gwapes
gwapes4w ago
try {
await somePromise()
} catch (e) {
//handle some error
}
try {
await somePromise()
} catch (e) {
//handle some error
}
Want results from more Discord servers?
Add your server