Skip to content

fix: move req.json() inside try/catch to handle invalid JSON body - #38

Open
memosr wants to merge 1 commit into
circlefin:masterfrom
memosr:fix/transfer-reqjson-try-catch
Open

fix: move req.json() inside try/catch to handle invalid JSON body#38
memosr wants to merge 1 commit into
circlefin:masterfrom
memosr:fix/transfer-reqjson-try-catch

Conversation

@memosr

@memosr memosr commented May 17, 2026

Copy link
Copy Markdown

Problem

In app/api/gateway/transfer/route.ts, the req.json() destructuring happens before the try block starts at line 46:

const { sourceChain, destinationChain, amount, recipientAddress } =
  await req.json();

try {
  // ...
}

This means:

  • Invalid JSON in the request body throws an uncaught SyntaxError, producing an unhandled 500 instead of a proper 400
  • The variables are referenced in the catch block (lines 241-244 for the failed-transaction logger) where they may be undefined

Fix

- const { sourceChain, destinationChain, amount, recipientAddress } =
-   await req.json();
+ let sourceChain: string | undefined;
+ let destinationChain: string | undefined;
+ let amount: string | undefined;
+ let recipientAddress: string | undefined;
 
  try {
+   ({ sourceChain, destinationChain, amount, recipientAddress } =
+     await req.json());

And at the top of catch:

if (error instanceof SyntaxError) {
  return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}

The SyntaxError check is intentionally first — before console.error and the INSUFFICIENT_GAS check — so malformed-body errors never get logged as unexpected transfer failures.

Impact

  • Correctness: Malformed JSON returns proper 400 instead of unhandled 500
  • Risk: Low — variables remain accessible in catch block via outer scope
  • Other routes checked: balance/route.ts and deposit/route.ts already call req.json() inside their try blocks, no changes needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant