Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | 154x 154x 153x 153x 153x 153x 153x 153x 153x 153x 153x 153x 1x 153x 1x 1x 15x 15x 15x 535x 535x 535x 30x 30x 24x 535x 36x 535x 535x 535x 9x 9x 6x 6x 36x 36x 535x 1x 1x 1x | import * as Sentry from "@sentry/react";
import { AxiosError } from "axios";
import { showMessage } from "@common/Toast";
import { ErrorCodeEnum } from "@services/api/api.constant";
/**
* Standardized error structure from backend API
*/
export interface ApiErrorResponse {
message: string;
code?: string;
input?: Array<{
param: string;
message: string;
}>;
statusCode?: number;
}
/**
* Parsed error information ready for display and handling
*/
export interface ParsedError {
message: string;
userMessage: string;
code?: string;
statusCode?: number;
fieldErrors?: Record<string, string>;
shouldRetry: boolean;
shouldRedirect: boolean;
isNetworkError: boolean;
}
/**
* Error context for checkout/payment operations
*/
export interface CheckoutErrorContext {
formId?: string;
userId?: string;
merchantId?: string;
amount?: number;
currency?: string;
cartItems?: number | unknown[];
paymentMethod?: string;
step?: string;
componentName?: string;
[key: string]: unknown;
}
/**
* Options for error capture
*/
export interface CaptureErrorOptions {
/** Error severity level (defaults to 'error') */
level?: Sentry.SeverityLevel;
/** Whether this is a critical error (defaults to true) */
isCritical?: boolean;
/** Additional tags to attach to the error */
tags?: Record<string, string | number | boolean>;
/** Additional context data */
context?: CheckoutErrorContext;
/** Component stack trace (from ErrorBoundary) */
componentStack?: string;
}
/**
* Captures checkout/payment errors and logs them to Sentry with proper context and tags.
* This is the centralized error logging utility for all payment-related errors.
*
* @param error - The error object to capture
* @param options - Configuration options for error capture
*
* @example
* ```tsx
* // Basic usage
* captureCheckoutError(new Error("Payment failed"));
*
* // With context
* captureCheckoutError(error, {
* context: {
* formId: "form-123",
* amount: 100,
* step: "payment-processing"
* }
* });
*
* // With custom severity and tags
* captureCheckoutError(error, {
* level: "warning",
* isCritical: false,
* tags: {
* custom_tag: "value"
* }
* });
* ```
*/
export function captureCheckoutError(
error: Error,
options: CaptureErrorOptions = {},
): void {
const {
level = "error",
isCritical = true,
tags = {},
context = {},
componentStack,
} = options;
Sentry.withScope((scope) => {
// Set error severity
scope.setLevel(level);
// Set standard payment/checkout tags
scope.setTag("error_type", "payment_component_crash");
scope.setTag("component_type", "payment");
scope.setTag("is_critical", isCritical);
// Add custom tags
Object.entries(tags).forEach(([key, value]) => {
scope.setTag(key, value);
});
// Add payment/checkout context
if (Object.keys(context).length > 0) {
scope.setContext("payment", context);
}
// Add component stack trace if provided (from error boundary)
if (componentStack) {
scope.setContext("componentStack", {
componentStack,
});
}
// Add error details
scope.setContext("errorDetails", {
message: error.message,
stack: error.stack,
name: error.name,
timestamp: new Date().toISOString(),
});
// Capture the error
Sentry.captureException(error);
});
// Log to console in development
if (process.env.NODE_ENV === "development") {
console.error("Checkout Error:", {
error,
level,
isCritical,
tags,
context,
});
}
}
/**
* Captures a warning-level checkout error (non-critical)
*
* @param error - The error object to capture
* @param context - Checkout context data
*/
export function captureCheckoutWarning(
error: Error,
context?: CheckoutErrorContext,
): void {
captureCheckoutError(error, {
level: "warning",
isCritical: false,
context,
});
}
/**
* Captures an info-level checkout event (for tracking non-error issues)
*
* @param message - The info message to log
* @param context - Checkout context data
*/
export function captureCheckoutInfo(
message: string,
context?: CheckoutErrorContext,
): void {
Sentry.withScope((scope) => {
scope.setLevel("info");
scope.setTag("event_type", "payment_info");
if (context && Object.keys(context).length > 0) {
scope.setContext("payment", context);
}
Sentry.captureMessage(message);
});
if (process.env.NODE_ENV === "development") {
console.info("Checkout Info:", message, context);
}
}
/**
* Extract error information from various error types.
* Handles Axios errors, network errors, and generic JavaScript errors.
* This is a generic utility that can be used anywhere in the application.
*
* @param error - The error to parse (can be any type)
* @returns ParsedError object with standardized error information
*
* @example
* ```tsx
* try {
* await apiCall();
* } catch (error) {
* const parsed = parseError(error);
* console.log(parsed.userMessage); // User-friendly message
* console.log(parsed.statusCode); // HTTP status code
* console.log(parsed.fieldErrors); // Field-specific validation errors
* }
* ```
*/
export function parseError(error: unknown): ParsedError {
// Network errors (no response from server)
Iif (error instanceof AxiosError && !error.response) {
return {
message: error.message || "Network error occurred",
userMessage:
"Unable to connect to the server. Please check your internet connection and try again.",
statusCode: 0,
shouldRetry: true,
shouldRedirect: false,
isNetworkError: true,
};
}
// Axios errors with response from server
if (error instanceof AxiosError && error.response) {
const data = error.response.data as ApiErrorResponse;
const statusCode = error.response.status;
// Parse field-specific validation errors
const fieldErrors: Record<string, string> = {};
Iif (data?.input && Array.isArray(data.input)) {
data.input.forEach((field) => {
fieldErrors[field.param] = field.message;
});
}
// Determine user-friendly message based on status code
let userMessage =
data?.message || "An error occurred while processing your request.";
// Special cases based on HTTP status code
Iif (statusCode === 401) {
userMessage = "Your session has expired. Please log in again.";
} else Iif (statusCode === 403) {
userMessage = "You don't have permission to perform this action.";
} else Iif (statusCode === 404) {
userMessage = "The requested resource was not found.";
} else Iif (statusCode === 429) {
userMessage = "Too many requests. Please wait a moment and try again.";
} else if (statusCode >= 500) {
userMessage = "A server error occurred. Please try again later.";
}
return {
message: data?.message || error.message,
userMessage,
code: data?.code,
statusCode,
fieldErrors:
Object.keys(fieldErrors).length > 0 ? fieldErrors : undefined,
shouldRetry: statusCode >= 500 || statusCode === 429,
shouldRedirect: statusCode === 401,
isNetworkError: false,
};
}
// Generic JavaScript errors
Eif (error instanceof Error) {
return {
message: error.message,
userMessage: "An unexpected error occurred. Please try again.",
shouldRetry: false,
shouldRedirect: false,
isNetworkError: false,
};
}
// Unknown error type (shouldn't happen, but handle gracefully)
return {
message: "Unknown error",
userMessage: "An unexpected error occurred. Please try again.",
shouldRetry: false,
shouldRedirect: false,
isNetworkError: false,
};
}
/**
* Handle error with consistent user notification and logging.
* This is a generic error handler that can be used throughout the entire application
* for any type of operation (API calls, form submissions, data processing, etc.).
*
* @param error - The error to handle
* @param options - Configuration options
* @returns ParsedError object for further processing if needed
*
* @example
* ```tsx
* // Basic usage - shows error message to user
* try {
* await apiCall();
* } catch (error) {
* handleError(error, {
* context: "apiCall",
* isDesktopView: true
* });
* }
*
* // With custom message
* handleError(error, {
* context: "submitForm",
* customMessage: "Unable to submit form. Please try again.",
* isDesktopView: isDesktop
* });
*
* // With form field errors
* handleError(error, {
* context: "validateForm",
* setFieldError: (field, message) => formik.setFieldError(field, message)
* });
*
* // Silent error (log only, no user notification)
* handleError(error, {
* context: "backgroundSync",
* silent: true
* });
* ```
*/
export function handleError(
error: unknown,
options: {
/** Context string for logging (e.g., "addToCart", "checkout") */
context?: string;
/** Custom message to show instead of parsed message */
customMessage?: string;
/** Function to set form field errors */
setFieldError?: (field: string, message: string) => void;
/** Whether the view is desktop (affects message styling) */
isDesktopView?: boolean;
/** If true, logs error but doesn't show message to user */
silent?: boolean;
/** Callback to invoke for retry logic */
onRetry?: () => void;
} = {},
): ParsedError {
const parsed = parseError(error);
// Log error for debugging (always log to console and Sentry)
if (options.context) {
console.error(`Error in ${options.context}:`, parsed.message, error);
} else {
console.error("Error:", parsed.message, error);
}
// Capture to Sentry for monitoring
if (error instanceof Error) {
captureCheckoutError(error, {
context: {
contextName: options.context,
statusCode: parsed.statusCode,
errorCode: parsed.code,
},
level:
parsed.statusCode && parsed.statusCode >= 500 ? "error" : "warning",
});
}
// Set field-specific errors if available and callback provided
if (parsed.fieldErrors && options.setFieldError) {
const setFieldError = options.setFieldError;
Object.entries(parsed.fieldErrors).forEach(([field, message]) => {
setFieldError(field, message);
});
}
// Show user notification unless silent mode
if (!options.silent) {
const messageToShow = options.customMessage || parsed.userMessage;
showMessage("Error", messageToShow, options.isDesktopView);
}
return parsed;
}
/**
* Type guard to check if an error is an AxiosError.
* This generic utility can be used anywhere in the application to safely check error types.
*
* @param error - The error to check
* @returns True if the error is an AxiosError
*
* @example
* ```tsx
* catch (error) {
* if (isAxiosError(error)) {
* console.log(error.response?.status);
* }
* }
* ```
*/
export function isAxiosError(error: unknown): error is AxiosError {
return error instanceof AxiosError;
}
/**
* Check if error has a specific HTTP status code.
* This generic utility can be used anywhere in the application to check status codes.
*
* @param error - The error to check
* @param statusCode - The status code to check for
* @returns True if the error has the specified status code
*
* @example
* ```tsx
* catch (error) {
* if (isStatusCode(error, 401)) {
* // Handle unauthorized
* } else if (isStatusCode(error, 404)) {
* // Handle not found
* }
* }
* ```
*/
export function isStatusCode(error: unknown, statusCode: number): boolean {
Iif (!isAxiosError(error)) return false;
return error.response?.status === statusCode;
}
/**
* Check if error indicates a network/connection issue.
* This generic utility can be used anywhere in the application to detect network errors.
*
* @param error - The error to check
* @returns True if the error is a network error
*
* @example
* ```tsx
* catch (error) {
* if (isNetworkError(error)) {
* showMessage("Error", "Please check your internet connection");
* }
* }
* ```
*/
export function isNetworkError(error: unknown): boolean {
if (isAxiosError(error)) {
return (
!error.response ||
error.code === "ECONNABORTED" ||
error.code === "ERR_NETWORK"
);
}
return false;
}
/**
* Extract user-friendly message from error (convenience function).
* This generic utility can be used anywhere in the application to quickly get error messages.
*
* @param error - The error to extract message from
* @param fallback - Fallback message if extraction fails
* @returns User-friendly error message
*
* @example
* ```tsx
* catch (error) {
* const message = getErrorMessage(error, "Operation failed");
* console.log(message);
* }
* ```
*/
export function getErrorMessage(
error: unknown,
fallback = "An error occurred",
): string {
const parsed = parseError(error);
return parsed.userMessage || fallback;
}
/**
* Wire code the API returns when the customer's email address must be
* verified before the checkout can proceed (a verification email was sent).
*/
export const EMAIL_VERIFICATION_REQUIRED_CODE = "email_verification_required";
export const CAPTCHA_CHALLENGE_REQUIRED_CODE = "captcha_challenge_required";
export const MAX_PAYMENT_CAPTCHA_CHALLENGES = 3;
/**
* Check if the error is the API's email-verification gate.
* Matched primarily by the `code` field, not the HTTP status: the gate and
* regular declines (e.g. "amount below minimum") both arrive as HTTP 400.
* A 400 without the code is only accepted when its message is the gate's
* message, so declines still fall through to failed-payment handling.
*/
export function isEmailVerificationRequiredError(error: unknown): boolean {
const parsed = parseError(error);
if (parsed.code === EMAIL_VERIFICATION_REQUIRED_CODE) return true;
return (
parsed.statusCode === ErrorCodeEnum.BAD_REQUEST &&
!!parsed.message?.toLowerCase().includes("needs to be verified")
);
}
/**
* The purchase hold. Distinct from EMAIL_VERIFICATION_REQUIRED: this one is
* cleared by a code, that one by a link. Code only, so it cannot claim either.
*/
export const PURCHASE_VERIFICATION_REQUIRED_CODE =
"purchase_verification_required";
export function isPurchaseVerificationRequiredError(error: unknown): boolean {
return parseError(error).code === PURCHASE_VERIFICATION_REQUIRED_CODE;
}
/** Wrong code, attempts still left: the buyer can correct it in place. */
export const VERIFICATION_CODE_INVALID_CODE = "verification_code_invalid";
/** Spent or retired by a newer code — retrying this one cannot ever succeed. */
export const VERIFICATION_CODE_EXHAUSTED_CODE = "verification_code_exhausted";
/** Nothing awaiting confirmation: never sent, or expired. */
export const NO_VERIFICATION_PENDING_CODE = "no_verification_pending";
/**
* The code the buyer typed was refused, whichever of the three ways.
* Distinguish with needsNewVerificationCode before deciding what to offer.
*/
export function isRejectedVerificationCodeError(error: unknown): boolean {
const { code } = parseError(error);
return (
code === VERIFICATION_CODE_INVALID_CODE ||
code === VERIFICATION_CODE_EXHAUSTED_CODE ||
code === NO_VERIFICATION_PENDING_CODE
);
}
/** Only a fresh code can get the buyer through; retrying this one cannot. */
export function needsNewVerificationCode(error: unknown): boolean {
const { code } = parseError(error);
return (
code === VERIFICATION_CODE_EXHAUSTED_CODE ||
code === NO_VERIFICATION_PENDING_CODE
);
}
export function isCaptchaChallengeRequiredError(error: unknown): boolean {
const parsed = parseError(error);
return parsed.code === CAPTCHA_CHALLENGE_REQUIRED_CODE;
}
export const isDisposableEmailError = (message?: string): boolean => {
Iif (!message) return false;
const lowerMessage = message.toLowerCase();
return (
lowerMessage.includes("disposable") || lowerMessage.includes("unreachable")
);
};
|