@@ -63,18 +63,34 @@ export async function action({ request }: ActionFunctionArgs) {
6363 return json ( { error : "Unauthorized" } , { status : 401 } ) ;
6464 }
6565
66+ // Parse JSON with separate error handling for malformed JSON
67+ let body : unknown ;
6668 try {
67- // Parse and validate the request body
68- const body = await request . json ( ) ;
69- const parsed = PlainCustomerCardRequestSchema . safeParse ( body ) ;
70-
71- if ( ! parsed . success ) {
72- logger . warn ( "Invalid Plain customer card request" , {
73- errors : parsed . error . errors ,
74- body,
69+ body = await request . json ( ) ;
70+ } catch ( error ) {
71+ // Handle JSON parsing errors as client errors (400) instead of server errors (500)
72+ if ( error instanceof SyntaxError || error instanceof TypeError ) {
73+ logger . warn ( "Malformed JSON in Plain customer card request" , {
74+ error : error . message ,
7575 } ) ;
76- return json ( { error : "Invalid request body" } , { status : 400 } ) ;
76+ return json ( { error : "Invalid JSON in request body" } , { status : 400 } ) ;
7777 }
78+ // Re-throw unexpected errors to be caught by outer catch
79+ throw error ;
80+ }
81+
82+ // Validate the request body schema
83+ const parsed = PlainCustomerCardRequestSchema . safeParse ( body ) ;
84+
85+ if ( ! parsed . success ) {
86+ logger . warn ( "Invalid Plain customer card request" , {
87+ errors : parsed . error . errors ,
88+ body,
89+ } ) ;
90+ return json ( { error : "Invalid request body" } , { status : 400 } ) ;
91+ }
92+
93+ try {
7894
7995 const { customer, cardKeys } = parsed . data ;
8096
0 commit comments