Magento – Magento 2 Payment Gateway – Howto show Gateway errors in Frontend

errormagento-2.1magento2paymentpayment-gateway

we are about developing a custom payment gateway plugin for one of our customers using the magento-sample-gateway-payment plugin as a draft in a Magento 2.1.4.

We have already successfully implemented the payment and if the gateway say's ok all works fine.

Our problem now is, that if the gateway refuses the payment, it will deliver one of many error messages. We want to show this error messages to the customer in the frontend.

Our Validator looks like this:

/**
 * Performs validation of result code
 *
 * @param array $validationSubject
 * @return ResultInterface
 */
public function validate(array $validationSubject)
{
    if (!isset($validationSubject['response']) || !is_array($validationSubject['response'])) {
        throw new \InvalidArgumentException('Response does not exist');
    }
    $response = $validationSubject['response'];
    if ($this->isSuccessfulTransaction($response)) {
        return $this->createResult(
            true,
            []
        );
    } else {
        // We have also tryed to throw a LocalizedException here like i saw in other payment plugins on github
        return $this->createResult(
            false,
            [__('My custom error message later out of $response')]
        );
    }
}

The problem is, no matter what we tryed the frontend always shows 'An error occurred on the server. Please try to place the order again.' and the actual error message gets only logged to the system.log

I hope someone is able to help me,

Greetings Sven

Best Answer

Generally this message is handle from two core files:

Magento\Checkout\Model\PaymentInformationManagement and Magento\Checkout\Model\GuestPaymentInformationManagement

from function savePaymentInformationAndPlaceOrder if you want to change default message and display your exception message then just

throw new CouldNotSaveException(
            __('An error occurred on the server. Please try to place the order again.'),
            $e
        );

replace above line with below code

throw new CouldNotSaveException(
            new \Magento\Framework\Phrase($e->getMessage()),
            $e
        );
Related Topic