This commit is contained in:
2026-01-18 23:53:31 +03:00
parent 17eec3ebc0
commit 6a7325f0fd
334 changed files with 1074 additions and 680 deletions

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Traits;
use Apoloz\AlfaBank\Exceptions\AlfaBankException;
use Saloon\Http\Response;
use Throwable;
trait HasAlfaErrorHandling
{
/**
* Determine if the request has failed.
*/
public function hasRequestFailed(Response $response): ?bool
{
if ($response->status() >= 400) {
return true;
}
$contentType = $response->header('Content-Type') ?? '';
if (str_contains($contentType, 'application/json')) {
$data = $response->json();
if (isset($data['error']) || (isset($data['ErrorCode']) && (string)$data['ErrorCode'] !== '0')) {
return true;
}
}
return false;
}
/**
* Get the custom exception for the failed request.
*/
public function getRequestException(Response $response, ?Throwable $senderException): ?Throwable
{
$requestId = $response->header('X-Request-ID') ?? 'Unknown';
$errorCode = 'UNKNOWN';
$errorDescription = 'No description';
$contentType = $response->header('Content-Type') ?? '';
if (str_contains($contentType, 'application/json')) {
$data = $response->json();
$errorCode = $data['error'] ?? $data['ErrorCode'] ?? 'HTTP_' . $response->status();
$errorDescription = $data['error_description'] ?? $data['message'] ?? 'Request failed';
} else {
$errorCode = 'HTTP_' . $response->status();
$errorDescription = 'Request failed with status ' . $response->status();
}
return new AlfaBankException(
$response,
(string)$errorCode,
"({$requestId}) {$errorDescription}"
);
}
}