Prevent Sentry Noise by Normalizing External API Errors

📖 1 minute read

When integrating with third-party APIs that return dynamic error references, you can end up with dozens of fragmented Sentry issues for the same underlying problem. The fix: catch the exception, parse the actual error code, and rethrow using your own exception type.

The Problem: External APIs often include unique request IDs or timestamps in error messages. Sentry treats each variation as a separate issue, creating noise.

The Solution: Extract the stable error code from the response body and use it to decide how to handle the exception.

This groups all occurrences under a single Sentry issue and lets you apply domain-specific handling (like stopping retries for permanently unavailable resources).

// Before: Each API error creates a separate Sentry issue
$product = $apiClient->getProduct($id);

// After: Parse error code and rethrow normalized exception
try {
    $product = $apiClient->getProduct($id);
} catch (ApiException $e) {
    $errorCode = json_decode(
        (string) $e->getPrevious()?->getResponse()->getBody(),
        true
    )['error'] ?? null;

    if (in_array($errorCode, ['PRODUCT_EXPIRED', 'PRODUCT_DISABLED'])) {
        // Throw domain exception that stops retries
        throw new InvalidResourceException(
            resourceId: $id,
            previous: $e
        );
    }

    throw $e; // Re-throw other errors as-is
}

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *