Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/mercadopago/sdk-java/llms.txt

Use this file to discover all available pages before exploring further.

The Mercado Pago Java SDK uses a structured exception hierarchy to distinguish between client-side SDK errors, API-level error responses, and webhook validation failures. Understanding which exception to catch — and what information each carries — lets you build precise, resilient error-handling logic without swallowing important context.

Exception hierarchy

java.lang.Exception
├── MPException                          (com.mercadopago.exceptions)
│   │   Base SDK exception for transport and internal errors
│   ├── MPInvalidWebhookSignatureException (com.mercadopago.exceptions)
│   │       Webhook signature validation failure
│   ├── MPJsonParseException             (com.mercadopago.exceptions)
│   │       JSON serialization / deserialization failure
│   └── MPMalformedRequestException      (com.mercadopago.exceptions)
│           Malformed request construction (raised before any network call)
└── MPApiException                       (com.mercadopago.exceptions)
        API returned HTTP 4xx or 5xx (extends Exception directly, not MPException)
MPApiException is not a subclass of MPException — it extends java.lang.Exception directly, just like MPException. Catch them separately in your catch chain. MPInvalidWebhookSignatureException does extend MPException, so a broad catch (MPException e) will also catch it.

MPException

Package: com.mercadopago.exceptions The base checked exception for all SDK-side failures that occur before, during, or after an API call — such as network I/O errors, connection timeouts, or unrecoverable internal SDK states. It is not used for API-level error responses (HTTP 4xx/5xx); those are represented by MPApiException.

Constructors

MPException(String message)
constructor
Constructs a new SDK exception with the specified human-readable detail message.
MPException(String message, Throwable cause)
constructor
Constructs a new SDK exception with a detail message and the underlying throwable that triggered it.
MPException(Throwable cause)
constructor
Constructs a new SDK exception wrapping an underlying cause. The message is derived from the cause.

Usage

Catch MPException when you want a single handler for all non-API SDK failures — transport errors, serialization problems, and malformed request construction:
import com.mercadopago.exceptions.MPException;
import com.mercadopago.exceptions.MPApiException;
import com.mercadopago.client.payment.PaymentClient;
import com.mercadopago.client.payment.PaymentCreateRequest;

PaymentClient client = new PaymentClient();

try {
    Payment payment = client.create(request);
} catch (MPApiException e) {
    // API returned 4xx/5xx — inspect status code and body
    System.err.println("API error " + e.getStatusCode() + ": " + e.getMessage());
} catch (MPException e) {
    // Transport, serialization, or request construction error
    System.err.println("SDK error: " + e.getMessage());
    if (e.getCause() != null) {
        e.getCause().printStackTrace();
    }
}

MPApiException

Package: com.mercadopago.exceptions Thrown when the Mercado Pago API returns an error response with an HTTP status code greater than 299. Unlike MPException, this exception represents a successfully received API response that indicates a business or validation error. It carries the full MPResponse so you can inspect headers, body, and status.

Fields

statusCode
int
required
The HTTP status code returned by the Mercado Pago API (e.g., 400, 401, 404, 500). Derived directly from the MPResponse.
apiResponse
MPResponse
required
The full MPResponse received from the API, including the response body (content), all response headers, and the status code.

Constructors

MPApiException(String message, MPResponse response)
constructor
Constructs an API exception with a human-readable description and the full API response.
MPApiException(String message, Throwable cause, MPResponse response)
constructor
Constructs an API exception with a detail message, an optional underlying throwable, and the API response. The cause may be null.

Methods

getStatusCode()
int
Returns the HTTP status code of the API error response.
getApiResponse()
MPResponse
Returns the full MPResponse attached to this exception.

MPResponse fields

The MPResponse returned by getApiResponse() exposes three fields:
getContent()
String
The raw response body as a UTF-8 string. For error responses this is typically a JSON object containing Mercado Pago error codes and messages. May be empty for responses with no body (e.g., HTTP 204).
getStatusCode()
Integer
The HTTP status code of the response (mirrors MPApiException.getStatusCode()).
getHeaders()
Map<String, List<String>>
All response headers keyed by header name, with multi-value support. Use this to retrieve x-request-id for support correlation.

Common API status codes

StatusMeaningTypical cause
400Bad RequestMissing or invalid request fields
401UnauthorizedInvalid or expired access token
404Not FoundResource ID does not exist
409ConflictDuplicate request with same idempotency key but different payload
422Unprocessable EntityBusiness rule violation (e.g., insufficient funds)
429Too Many RequestsRate limit exceeded
500Internal Server ErrorTransient Mercado Pago server error — retry with back-off

Usage example

import com.mercadopago.exceptions.MPApiException;
import com.mercadopago.net.MPResponse;
import java.util.List;

try {
    Payment payment = client.create(request);
} catch (MPApiException e) {
    MPResponse response = e.getApiResponse();

    // Always log the request ID for support correlation
    List<String> requestIds = response.getHeaders().get("x-request-id");
    String requestId = (requestIds != null && !requestIds.isEmpty())
        ? requestIds.get(0)
        : "unavailable";

    System.err.printf("Status: %d%n", e.getStatusCode());
    System.err.printf("Request-ID: %s%n", requestId);
    System.err.printf("Body: %s%n", response.getContent());

    if (e.getStatusCode() == 429) {
        // Implement exponential back-off before retrying
    }
}
Always extract and log the x-request-id response header from MPApiException.getApiResponse().getHeaders() before escalating errors. Mercado Pago support uses this identifier to correlate server-side logs with your request.

MPJsonParseException

Package: com.mercadopago.exceptions Thrown when JSON serialization or deserialization fails inside the SDK’s Serializer. Common causes include malformed JSON in an API response, unexpected field types, or missing required properties. This exception is a subclass of MPException.

Constructors

MPJsonParseException(String message)
constructor
Constructs a new JSON parse exception with a human-readable description of the parsing error.
MPJsonParseException(String message, Throwable throwable)
constructor
Constructs a new JSON parse exception with a detail message and the underlying throwable (e.g., a Gson or I/O exception) that caused the failure.

Usage

MPJsonParseException is generally not thrown by normal API interactions. You may encounter it if the API returns an unexpected response format or if you are working with the SDK’s serialization utilities directly.
import com.mercadopago.exceptions.MPJsonParseException;
import com.mercadopago.exceptions.MPApiException;
import com.mercadopago.exceptions.MPException;

try {
    Payment payment = client.get(paymentId);
} catch (MPApiException e) {
    // API-level error
} catch (MPJsonParseException e) {
    // Response could not be deserialized — log the raw cause
    System.err.println("JSON parse failure: " + e.getMessage());
    if (e.getCause() != null) {
        e.getCause().printStackTrace();
    }
} catch (MPException e) {
    // Other SDK-side error
}

MPMalformedRequestException

Package: com.mercadopago.exceptions Thrown before any network call when the SDK cannot construct a valid MPRequest due to invalid or incomplete input — for example, a missing required field, a malformed URL, or an encoding failure. This exception indicates a programming error on the caller’s side rather than an API or network failure. It is a subclass of MPException.

Constructors

MPMalformedRequestException(String message)
constructor
Constructs a new malformed request exception with a human-readable description of the request construction error.
MPMalformedRequestException(Throwable cause)
constructor
Constructs a new malformed request exception wrapping the underlying throwable that prevented request construction.

MPInvalidWebhookSignatureException

Package: com.mercadopago.exceptions Thrown by WebhookSignatureValidator when a webhook notification cannot be confirmed as originating from Mercado Pago. This exception extends MPException and carries structured context — failure reason, request ID, and timestamp — to support correlation against the Mercado Pago notifications dashboard without exposing internal details in your HTTP responses.

Fields

reason
SignatureFailureReason
required
The specific failure mode that caused validation to fail. See SignatureFailureReason below for all possible values.
requestId
String
The x-request-id header value from the incoming webhook request, when available. May be null if the header was absent or validation failed before the header could be read.
timestamp
String
The ts value extracted from the x-signature header at the point of failure, when parsing reached that point. May be null for early-failure reasons such as MISSING_SIGNATURE_HEADER.

Constructor

MPInvalidWebhookSignatureException(SignatureFailureReason reason, String requestId, String timestamp)
constructor
Creates a new invalid webhook signature exception. The detail message is automatically set to "Invalid webhook signature: " + reason.

Methods

getReason()
SignatureFailureReason
Returns the SignatureFailureReason enum value describing why validation failed.
getRequestId()
String
Returns the x-request-id header value, or null if unavailable.
getTimestamp()
String
Returns the ts value from the signature header, or null if unavailable.

SignatureFailureReason

Package: com.mercadopago.exceptions Enum that enumerates every reason WebhookSignatureValidator may reject a Mercado Pago webhook notification. Log this value alongside the x-request-id to correlate against the Mercado Pago notifications dashboard.
ValueDescription
MISSING_SIGNATURE_HEADERThe x-signature header was missing, empty, or contained only whitespace.
MALFORMED_SIGNATURE_HEADERThe header was present but did not match the expected ts=...,vN=... format.
MISSING_TIMESTAMPThe header parsed correctly but no ts= component was present.
MISSING_HASHNo hash was found in the header for any supported version. Typically indicates the SDK needs to be upgraded to support a new signature version.
SIGNATURE_MISMATCHThe computed HMAC did not match the value in the header. Most often caused by an incorrect secret or a forged request.
TIMESTAMP_OUT_OF_TOLERANCEThe header timestamp fell outside the configured tolerance window relative to the current clock. May indicate server clock drift or a replay attack.

Complete try/catch example

The following example shows a fully defensive catch chain that handles every exception the SDK can throw for a typical API resource operation:
import com.mercadopago.MercadoPagoConfig;
import com.mercadopago.client.payment.PaymentClient;
import com.mercadopago.client.payment.PaymentCreateRequest;
import com.mercadopago.exceptions.MPApiException;
import com.mercadopago.exceptions.MPInvalidWebhookSignatureException;
import com.mercadopago.exceptions.MPJsonParseException;
import com.mercadopago.exceptions.MPMalformedRequestException;
import com.mercadopago.exceptions.MPException;
import com.mercadopago.net.MPResponse;
import java.util.List;

MercadoPagoConfig.setAccessToken("APP_USR-your-access-token");
PaymentClient client = new PaymentClient();

try {
    Payment payment = client.create(buildPaymentRequest());
    System.out.println("Payment created: " + payment.getId());

} catch (MPApiException e) {
    // The API responded with an error status (> 299).
    MPResponse response = e.getApiResponse();

    // Extract the request ID for support correlation — always log this.
    List<String> requestIds = response.getHeaders().get("x-request-id");
    String requestId = (requestIds != null && !requestIds.isEmpty())
        ? requestIds.get(0)
        : "unavailable";

    System.err.printf("[MPApiException] status=%d requestId=%s%n",
        e.getStatusCode(), requestId);
    System.err.printf("Body: %s%n", response.getContent());

    switch (e.getStatusCode()) {
        case 401:
            System.err.println("Access token is invalid or expired. Refresh credentials.");
            break;
        case 422:
            System.err.println("Business rule violation. Check payment request fields.");
            break;
        case 429:
            System.err.println("Rate limit hit. Back off and retry.");
            break;
        case 500:
            System.err.println("Transient server error. Retry with exponential back-off.");
            break;
        default:
            System.err.println("Unhandled API error. Review the response body.");
    }

} catch (MPMalformedRequestException e) {
    // The request could not be constructed — this is a programming error.
    System.err.println("[MPMalformedRequestException] Fix your request: " + e.getMessage());

} catch (MPJsonParseException e) {
    // Deserialization of the API response failed.
    System.err.println("[MPJsonParseException] " + e.getMessage());
    if (e.getCause() != null) {
        e.getCause().printStackTrace();
    }

} catch (MPException e) {
    // Covers all other SDK-side failures: transport errors, I/O, etc.
    System.err.println("[MPException] " + e.getMessage());
    if (e.getCause() != null) {
        e.getCause().printStackTrace();
    }
}
For webhook signature validation, catch MPInvalidWebhookSignatureException and log the reason, requestId, and timestamp fields before returning an HTTP 400 to the caller:
import com.mercadopago.exceptions.MPInvalidWebhookSignatureException;
import com.mercadopago.exceptions.SignatureFailureReason;
import com.mercadopago.webhook.WebhookSignatureValidator;

try {
    WebhookSignatureValidator.validate(requestBody, xSignature, xRequestId, secret, null);
} catch (MPInvalidWebhookSignatureException e) {
    // Log structured context — never expose internals in the HTTP response body.
    System.err.printf(
        "[WebhookSignatureError] reason=%s requestId=%s timestamp=%s%n",
        e.getReason(), e.getRequestId(), e.getTimestamp());

    if (e.getReason() == SignatureFailureReason.TIMESTAMP_OUT_OF_TOLERANCE) {
        System.err.println("Check for server clock drift or replay attack.");
    }

    // Return HTTP 400 to the caller
    response.sendError(400, "Invalid webhook signature");
}

Build docs developers (and LLMs) love