refactor
This commit is contained in:
58
src/Traits/HasAlfaErrorHandling.php
Normal file
58
src/Traits/HasAlfaErrorHandling.php
Normal 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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user