x402 icon indicating copy to clipboard operation
x402 copied to clipboard

Fix error serialization in payment middleware responses

Open madisoncarter1234 opened this issue 2 months ago • 5 comments

Summary

Fixes a bug where Error objects were being serialized to JSON in payment middleware error responses, resulting in empty objects {} instead of meaningful error messages.

Problem

When JavaScript Error objects are passed to JSON.stringify(), they serialize to empty objects:

JSON.stringify({error: new Error('test')}) // {"error":{}}

This affected all error responses in the x402 payment middleware across Express, Next.js, and Hono implementations. Clients would receive responses like:

{"x402Version": 1, "error": {}, "accepts": [...]}

Making debugging impossible.

Solution

Changed error handling in catch blocks to extract the error message:

// Before
error: error instanceof Error ? error : "Fallback message"

// After  
error: error instanceof Error ? error.message : "Fallback message"

Changes

  • x402-express (src/index.ts): Fixed 3 catch blocks at lines 248, 282, 335
  • x402-next (src/index.ts): Fixed 2 catch blocks at lines 275, 343
  • x402-hono (src/index.ts): Fixed 2 catch blocks at lines 248, 312
  • Updated all test files to expect string error messages instead of Error objects

Testing

All tests pass:

  • x402-express: 30 tests passed
  • x402-next: 35 tests passed
  • x402-hono: 36 tests passed

Clients now receive proper error messages:

{"x402Version": 1, "error": "Invalid payment", "accepts": [...]}

madisoncarter1234 avatar Oct 27 '25 18:10 madisoncarter1234

🟡 Heimdall Review Status

Requirement Status More Info
Reviews 🟡 0/1
Denominator calculation
Show calculation
1 if user is bot 0
1 if user is external 0
2 if repo is sensitive 0
From .codeflow.yml 1
Additional review requirements
Show calculation
Max 0
0
From CODEOWNERS 0
Global minimum 0
Max 1
1
1 if commit is unverified 1
Sum 2

cb-heimdall avatar Oct 27 '25 18:10 cb-heimdall

@madisoncarter1234 is attempting to deploy a commit to the Coinbase Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar Oct 27 '25 18:10 vercel[bot]