#trycatch in httpaction
1 messages · Page 1 of 1 (latest)
If your try/catch block in a Convex httpAction isn't returning your custom response from the catch block, there are a few things to consider:
-
Returning a Response in the Catch Block:
You should ensure that your catch block is returning a validResponseobject. For example:import { httpAction } from "./_generated/server"; export const myHttpAction = httpAction(async (ctx, request) => { try { // ... your logic return new Response("Success", { status: 200 }); } catch (error) { return new Response("Custom error message", { status: 400 }); } });This pattern is shown in Convex documentation and community examples, where the catch block returns a custom
Responseobject with your desired status and message. This should work as expected in Convex httpActions, and is the recommended way to handle and return custom error responses in HTTP endpoints Webhook endpoint implementation. -
CORS and Headers:
If your endpoint is being called from a browser, make sure you are also setting the appropriate CORS headers in your error response, otherwise the browser may block the response or not expose the body. For example:return new Response("Custom error", { status: 400, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", } });This is especially important if you are handling authentication or custom headers Discord: CORS in httpAction.
-
Error Serialization:
If you try to return the error object directly (e.g.,return new Response(error, ...)), it may not serialize as you expect. Instead, useerror.messageorJSON.stringify(error)if you want to include error details. -
Production Error Stripping:
Note that in production, Convex may strip error messages for security reasons, so you may not see your custom error message in the client if you are not explicitly returning it in the response body Discord: Handling Convex Auth signIn errors in prod.
If you are following these patterns and still not seeing your custom response, please double-check that you are not throwing another error inside the catch block, and that your client is correctly handling the HTTP response.