X-Git-Url: https://git.m6w6.name/?p=pharext%2Fpharext.org;a=blobdiff_plain;f=app%2FGithub%2FException%2FRequestException.php;h=49ea1ae72f9a5db3fa805299cb48b732bfb886e9;hp=bb78982dd07b61efdad78963321ac52e38a1c149;hb=07b87ac26f62bc3c069bb16983fe7500272e19b4;hpb=ff1d11c17adb6453aa50dfd6169317e077240eef diff --git a/app/Github/Exception/RequestException.php b/app/Github/Exception/RequestException.php index bb78982..49ea1ae 100644 --- a/app/Github/Exception/RequestException.php +++ b/app/Github/Exception/RequestException.php @@ -3,7 +3,55 @@ 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) { + $errors .= sprintf($reasons[$error->code], $error->resource, $error->field); + } + return $errors; + } + function __toString() { + return parent::__toString() . "\n". $this->getErrorsAsString(); + } }