|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Opensaucesystems\Lxd\HttpClient\Plugin; |
| 4 | + |
| 5 | +use Http\Promise\Promise; |
| 6 | +use Http\Client\Common\Plugin; |
| 7 | +use Psr\Http\Message\RequestInterface; |
| 8 | +use Psr\Http\Message\ResponseInterface; |
| 9 | +use Http\Client\Exception\HttpException; |
| 10 | +use Opensaucesystems\Lxd\Exception\BadRequestException; |
| 11 | +use Opensaucesystems\Lxd\Exception\OperationException; |
| 12 | +use Opensaucesystems\Lxd\Exception\AuthenticationFailedException; |
| 13 | +use Opensaucesystems\Lxd\Exception\NotFoundException; |
| 14 | +use Opensaucesystems\Lxd\Exception\ConflictException; |
| 15 | + |
| 16 | +/** |
| 17 | + * Handle LXD errors. |
| 18 | + */ |
| 19 | +class LxdExceptionThrower implements Plugin |
| 20 | +{ |
| 21 | + /** |
| 22 | + * {@inheritdoc} |
| 23 | + */ |
| 24 | + public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise |
| 25 | + { |
| 26 | + return $next($request)->then( |
| 27 | + function (ResponseInterface $response) { |
| 28 | + // Successful response, just return it. |
| 29 | + return $response; |
| 30 | + }, |
| 31 | + function (\Throwable $e) use ($request) { |
| 32 | + if ($e instanceof HttpException) { |
| 33 | + $response = $e->getResponse(); |
| 34 | + $status = $response->getStatusCode(); |
| 35 | + |
| 36 | + switch ($status) { |
| 37 | + case 400: |
| 38 | + throw new BadRequestException($request, $response, $e); |
| 39 | + case 401: |
| 40 | + throw new OperationException($request, $response, $e); |
| 41 | + case 403: |
| 42 | + throw new AuthenticationFailedException($request, $response, $e); |
| 43 | + case 404: |
| 44 | + throw new NotFoundException($request, $response, $e); |
| 45 | + case 409: |
| 46 | + throw new ConflictException($request, $response, $e); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + // Rethrow unhandled exceptions |
| 51 | + throw $e; |
| 52 | + } |
| 53 | + ); |
| 54 | + } |
| 55 | +} |
0 commit comments