diff --git a/actions/payment.ts b/actions/payment.ts index 33143e5..0376333 100644 --- a/actions/payment.ts +++ b/actions/payment.ts @@ -295,16 +295,17 @@ export async function verifyDevicePayment( payment: result, }; } catch (error: unknown) { + const fallback = + "Unable to verify payment. Please try again or contact support."; if (error instanceof Error) { return { - message: - error.message || "Payment verification failed. Please try again.", + message: error.message || fallback, success: false, fieldErrors: {}, }; } else { return { - message: "Payment verification failed.", + message: fallback, success: false, fieldErrors: {}, }; @@ -365,16 +366,17 @@ export async function verifyTopupPayment( transaction: result.transaction, }; } catch (error: unknown) { + const fallback = + "Unable to verify payment. Please try again or contact support."; if (error instanceof Error) { return { - message: - error.message || "Please check your payment details and try again.", + message: error.message || fallback, success: false, fieldErrors: {}, }; } else { return { - message: "Topup verification failed.", + message: fallback, success: false, fieldErrors: {}, }; diff --git a/utils/tryCatch.ts b/utils/tryCatch.ts index e218448..0bf7583 100644 --- a/utils/tryCatch.ts +++ b/utils/tryCatch.ts @@ -11,29 +11,47 @@ export async function handleApiResponse( response: Response, fnName?: string, ) { - const responseData = await response.json(); + // The backend (or an upstream gateway) can respond with a non-JSON body — + // e.g. an HTML error page on a 5xx. Parsing that as JSON throws a cryptic + // "Unexpected token '<'" error, so read the body defensively instead. + const rawBody = await response.text(); + let responseData: Record = {}; + try { + responseData = rawBody ? JSON.parse(rawBody) : {}; + } catch { + if (!response.ok) { + console.log( + `Non-JSON API error response from ${fnName} (status ${response.status}):`, + rawBody.slice(0, 500), + ); + throw new Error("Please try again or contact support."); + } + } if (response.status === 401) { console.log("response data", responseData); throw new Error("UNAUTHORIZED"); } + const message = responseData.message as string | undefined; + const detail = responseData.detail as string | undefined; + if (response.status === 403) { throw new Error( - responseData.message || + message || "Forbidden; you do not have permission to access this resource.", ); } if (response.status === 429) { throw new Error( - responseData.message || "Too many requests; please try again later.", + message || "Too many requests; please try again later.", ); } if (!response.ok) { console.log(`API Error Response from ${fnName}:`, responseData); throw new Error( - responseData.message || responseData.detail || "Something went wrong.", + message || detail || "Something went wrong.", ); }