X-Git-Url: https://git.m6w6.name/?a=blobdiff_plain;ds=inline;f=lib%2FException%2FRequestException.php;fp=lib%2FException%2FRequestException.php;h=877664e13ea458f17ed18ed639c2a4360f9d7c5b;hb=8ef054b51c681e7822133b38f7c5ed9dd2a0f29c;hp=0000000000000000000000000000000000000000;hpb=3ed732562787562d0115a3cbef3f0f5129473b7d;p=m6w6%2Fseekat diff --git a/lib/Exception/RequestException.php b/lib/Exception/RequestException.php new file mode 100644 index 0000000..877664e --- /dev/null +++ b/lib/Exception/RequestException.php @@ -0,0 +1,69 @@ +response = $response; + + if (($h = $response->getHeader("Content-Type", Header::class)) + && $h->match("application/json", Header::MATCH_WORD) + && $failure = json_decode($response->getBody())) { + $message = $failure->message; + if (isset($failure->errors)) { + $this->errors = (array) $failure->errors; + } + } else { + $message = trim($response->getBody()->toString()); + } + + if (!strlen($message)) { + $message = $response->getTransferInfo("error"); + } + if (!strlen($message)) { + $message = $response->getResponseStatus(); + } + + parent::__construct($message, $response->getResponseCode(), null); + } + + function getErrors() : array { + return $this->errors; + } + + function getErrorsAsString() { + static $reasons = [ + "missing" => "The resource %1\$s does not exist\n", + "missing_field" => "Missing field %2\$s of resource %1\$s\n", + "invalid" => "Invalid formatting of field %2\$s of resource %1\$s\n", + "already_exists" => "A resource %1\$s with the same value of field %2\$s already exists\n", + ]; + + if (!$this->errors) { + return $this->response; + } + + $errors = "JSON errors:\n"; + foreach ($this->errors as $error) { + if ($error->code === "custom") { + $errors .= $error->message . "\n"; + } else { + $errors .= sprintf($reasons[$error->code], $error->resource, $error->field); + } + } + return $errors; + } + + function __toString() : string { + return parent::__toString() . "\n". $this->getErrorsAsString(); + } +}