Fix error serialization in payment middleware responses
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": [...]}
🟡 Heimdall Review Status
| Requirement | Status | More Info | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Reviews |
🟡
0/1
|
Denominator calculation
|
@madisoncarter1234 is attempting to deploy a commit to the Coinbase Team on Vercel.
A member of the Team first needs to authorize it.