Skip to content

Commit 8030d32

Browse files
committed
Handle HTTP 400 response from LXD for better handling of error messages
Without this you end up with getting json strings that get truncated, nobody wants to try reading that.
1 parent 05d0351 commit 8030d32

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/Exception/BadRequestException.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace Opensaucesystems\Lxd\Exception;
4+
5+
use Http\Client\Exception\HttpException;
6+
use Psr\Http\Message\RequestInterface;
7+
use Psr\Http\Message\ResponseInterface;
8+
9+
class BadRequestException extends HttpException
10+
{
11+
private $fallbackMessage = "LXD produced an error state but we could not parse the response";
12+
13+
public function __construct(RequestInterface $request, ResponseInterface $response, \Exception $previous = null)
14+
{
15+
$content = json_decode($response->getBody()->getContents(), true);
16+
17+
$message = json_last_error() !== 0 ? $this->fallbackMessage : $content["error"];
18+
19+
parent::__construct($message, $request, $response, $previous);
20+
}
21+
}

src/HttpClient/Plugin/LxdExceptionThower.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Psr\Http\Message\RequestInterface;
77
use Psr\Http\Message\ResponseInterface;
88
use Http\Client\Exception\HttpException;
9+
use Opensaucesystems\Lxd\Exception\BadRequestException;
910
use Opensaucesystems\Lxd\Exception\OperationException;
1011
use Opensaucesystems\Lxd\Exception\AuthenticationFailedException;
1112
use Opensaucesystems\Lxd\Exception\NotFoundException;
@@ -23,25 +24,29 @@ class LxdExceptionThower implements Plugin
2324
public function handleRequest(RequestInterface $request, callable $next, callable $first)
2425
{
2526
$promise = $next($request);
26-
27+
2728
return $promise->then(function (ResponseInterface $response) use ($request) {
2829
return $response;
2930
}, function (\Exception $e) use ($request) {
3031
if (get_class($e) === HttpException::class) {
3132
$response = $e->getResponse();
3233

34+
if (400 === $response->getStatusCode()) {
35+
throw new BadRequestException($request, $response, $e);
36+
}
37+
3338
if (401 === $response->getStatusCode()) {
3439
throw new OperationException($request, $response, $e);
3540
}
3641

3742
if (403 === $response->getStatusCode()) {
3843
throw new AuthenticationFailedException($request, $response, $e);
3944
}
40-
45+
4146
if (404 === $response->getStatusCode()) {
4247
throw new NotFoundException($request, $response, $e);
4348
}
44-
49+
4550
if (409 === $response->getStatusCode()) {
4651
throw new ConflictException($request, $response, $e);
4752
}

0 commit comments

Comments
 (0)