3 namespace seekat\Exception
;
8 use http\Client\Response
;
10 class RequestException
extends \Exception
implements Exception
15 function __construct(Response
$response) {
16 $this->response
= $response;
18 if (($h = $response->getHeader("Content-Type", Header
::class))
19 && $h->match("application/json", Header
::MATCH_WORD
)
20 && $failure = json_decode($response->getBody())) {
21 $message = $failure->message
;
22 if (isset($failure->errors
)) {
23 $this->errors
= (array) $failure->errors
;
26 $message = trim($response->getBody()->toString());
29 if (!strlen($message)) {
30 $message = $response->getTransferInfo("error");
32 if (!strlen($message)) {
33 $message = $response->getResponseStatus();
36 parent
::__construct($message, $response->getResponseCode(), null);
39 function getErrors() : array {
43 function getErrorsAsString() {
45 "missing" => "The resource %1\$s does not exist\n",
46 "missing_field" => "Missing field %2\$s of resource %1\$s\n",
47 "invalid" => "Invalid formatting of field %2\$s of resource %1\$s\n",
48 "already_exists" => "A resource %1\$s with the same value of field %2\$s already exists\n",
52 return $this->response
;
55 $errors = "JSON errors:\n";
56 foreach ($this->errors
as $error) {
57 if ($error->code
=== "custom") {
58 $errors .= $error->message
. "\n";
60 $errors .= sprintf($reasons[$error->code
], $error->resource, $error->field
);
66 function __toString() : string {
67 return parent
::__toString() . "\n". $this->getErrorsAsString();