1: | <?php |
2: | |
3: | namespace IPay\Http\Plugins; |
4: | |
5: | use Http\Client\Common\Plugin; |
6: | use Http\Promise\Promise; |
7: | use IPay\Exceptions\LoginException; |
8: | use IPay\Exceptions\SessionException; |
9: | use Nette\Utils\Json; |
10: | use Psr\Http\Message\RequestInterface; |
11: | use Psr\Http\Message\ResponseInterface; |
12: | |
13: | final class ExceptionThrower implements Plugin |
14: | { |
15: | public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise |
16: | { |
17: | return $next($request)->then(function (ResponseInterface $response): ResponseInterface { |
18: | if (200 !== $response->getStatusCode()) { |
19: | $error = Json::decode((string) $response->getBody()); |
20: | |
21: | throw self::createException($error); |
22: | } |
23: | |
24: | return $response; |
25: | }); |
26: | } |
27: | |
28: | |
29: | |
30: | |
31: | private static function createException(\stdClass $error): \Throwable |
32: | { |
33: | |
34: | $class = match ($error->errorCode) { |
35: | 'LOGON_CREDENTIALS_REJECTED' => LoginException::class, |
36: | '96', '99' => SessionException::class, |
37: | default => \RuntimeException::class, |
38: | }; |
39: | |
40: | return new $class($error->errorMessage ?? 'Unknown error.'); |
41: | } |
42: | } |
43: | |