06bc96032b5b37b6bb3830fd7847c46bcabe8f6f
3 namespace seekat\Exception
;
5 use http\
{Client\Response
, Header
};
9 * @code-coverage-ignore
11 class RequestException
extends \Exception
implements Exception
{
19 * The response of the request which caused the exception
25 * @param Response $response
27 function __construct(Response
$response) {
28 $this->response
= $response;
30 if (($h = $response->getHeader("Content-Type", Header
::class))
31 && $h->match("application/json", Header
::MATCH_WORD
)
32 && $failure = json_decode($response->getBody())) {
33 $message = $failure->message
;
34 if (isset($failure->errors
)) {
35 $this->errors
= (array) $failure->errors
;
38 $message = trim($response->getBody()->toString());
41 if (!strlen($message)) {
42 $message = $response->getTransferInfo("error");
44 if (!strlen($message)) {
45 $message = $response->getResponseStatus();
48 parent
::__construct($message, $response->getResponseCode(), null);
55 function getErrors() : array {
62 function getResponse() : Response
{
63 return $this->response
;
67 * Combine any errors into a single string
68 * @staticvar array $reasons
71 function getErrorsAsString() {
73 "missing" => "The resource %1\$s does not exist\n",
74 "missing_field" => "Missing field %2\$s of resource %1\$s\n",
75 "invalid" => "Invalid formatting of field %2\$s of resource %1\$s\n",
76 "already_exists" => "A resource %1\$s with the same value of field %2\$s already exists\n",
80 return $this->response
;
83 $errors = "JSON errors:\n";
84 foreach ($this->errors
as $error) {
85 if ($error->code
=== "custom") {
86 $errors .= $error->message
. "\n";
88 $errors .= sprintf($reasons[$error->code
], $error->resource, $error->field
);
97 function __toString() : string {
98 return parent
::__toString() . "\n". $this->getErrorsAsString();