X-Git-Url: https://git.m6w6.name/?a=blobdiff_plain;ds=sidebyside;f=app%2FGithub%2FException%2FRequestException.php;h=c0a3d33c71524b3438dc7528759460763d839c6d;hb=e7943cab5bdac9b214a065edf129cecc5db20af7;hp=bb78982dd07b61efdad78963321ac52e38a1c149;hpb=ebc0d017c8a24bd16ca1f4347b39b07ba4349135;p=pharext%2Fpharext.org diff --git a/app/Github/Exception/RequestException.php b/app/Github/Exception/RequestException.php index bb78982..c0a3d33 100644 --- a/app/Github/Exception/RequestException.php +++ b/app/Github/Exception/RequestException.php @@ -3,7 +3,60 @@ namespace app\Github\Exception; use app\Github\Exception; +use http\Header; +use http\Client\Response; -interface RequestException extends Exception +class RequestException extends \Exception implements Exception { + protected $errors = []; + + function __construct(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 = $response->getBody()->toString(); + } + + if (!strlen($message)) { + $message = $response->getTransferInfo("error"); + } + + parent::__construct($message, $response->getResponseCode(), null); + } + + function getErrors() { + 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 ""; + } + + $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() { + return parent::__toString() . "\n". $this->getErrorsAsString(); + } }