Skip to content

Latest commit

 

History

History
173 lines (138 loc) · 10.3 KB

README.md

File metadata and controls

173 lines (138 loc) · 10.3 KB

Build Status Coverage Status CodeCov

Total Downloads Monthly Downloads

StyleCI PHP-Eye PHPStan

HttpExceptions

All HTTP statuses from RFC 7231 implemented as separated Exceptions.

These Exceptions support a straightforward implementation of the IETF Problem Details for HTTP APIs RFC 7807.

abstract HttpException class and its subclasses provide exceptions corresponding to HTTP error status codes. The most common are included, but you can create exceptions for other status codes by using (or subclassing) HttpException and providing the reason phrase as the $title and the status code as the $statusCode.

This package provides the following exception classes in the Chiron\Http\Exception\Client namespace for 4xx http errors. And Chiron\Http\Exception\Server namespace for 5xx http errors.

4xx: Client Error - The request contains bad syntax or cannot be fulfilled 5xx: Server Error - The server failed to fulfill an apparently valid request

Client errors :

Exception Code Message
BadRequestHttpException 400 "Bad Request"
UnauthorizedHttpException 401 "Unauthorized"
PaymentRequiredHttpException 402 "Payment Required"
ForbiddenHttpException 403 "Forbidden"
NotFoundHttpException 404 "Not Found"
MethodNotAllowedHttpException 405 "Method Not Allowed"
NotAcceptableHttpException 406 "Not Acceptable"
ProxyAuthenticationRequiredHttpException 407 "Proxy Authentication Required"
RequestTimeoutHttpException 408 "Request Timeout"
ConflictHttpException 409 "Conflict"
GoneHttpException 410 "Gone"
LengthRequiredHttpException 411 "Length Required"
PreconditionFailedHttpException 412 "Precondition Failed"
PayloadTooLargeHttpException 413 "Payload Too Large"
UriTooLongHttpException 414 "URI Too Long"
UnsupportedMediaTypeHttpException 415 "Unsupported Media Type"
RangeNotSatisfiableHttpException 416 "Range Not Satisfiable"
ExpectationFailedHttpException 417 "Expectation Failed"
MisdirectedRequestHttpException 421 "Misdirected Request"
UnprocessableEntityHttpException 422 "Unprocessable Entity"
LockedHttpException 423 "Locked"
FailedDependencyHttpException 424 "Failed Dependency"
TooEarlyHttpException 425 "Too Early"
UpgradeRequiredHttpException 426 "Upgrade Required"
PreconditionRequiredHttpException 428 "Precondition Required"
TooManyRequestsHttpException 429 "Too Many Requests"
RequestHeaderFieldsTooLargeHttpException 431 "Request Header Fields Too Large"
UnavailableForLegalReasonsHttpException 451 "Unavailable For Legal Reasons"

Server errors :

Exception Code Message
InternalServerErrorHttpException 500 "Internal Server Error"
NotImplementedHttpException 501 "'Not Implemented"
BadGatewayHttpException 502 "Bad Gateway"
ServiceUnavailableHttpException 503 "Service Unavailable"
GatewayTimeoutHttpException 504 "Gateway Timeout"
HttpVersionNotSupportedHttpException 505 "HTTP Version Not Supported"
VariantAlsoNegotiatesHttpException 506 "Variant Also Negotiates"
InsufficientStorageHttpException 507 "Insufficient Storage"
LoopDetectedHttpException 508 "Loop Detected"
NotExtendedHttpException 510 "Not Extended"
NetworkAuthenticationRequiredHttpException 511 "Network Authentication Required"

References for HTTP status code

Basic Usage

Throw an exception.

throw new \Chiron\Http\Exception\Client\BadRequestHttpException(); 

Throw an exception with a custom message.

$e = new \Chiron\Http\Exception\Client\BadRequestHttpException("Invalid syntax !");
throw $e->setHeaders(['X-Custom-Header' => 'foobar']);

Catch an exception and output an HTML response.

try {
    // ... 
} catch (\Chiron\Http\Exception\HttpException $e) {
    http_response_code($e->getStatusCode());
    header("Content-type: text/html");
    print "<h1>" . $e->getMessage() . "</h1>";
}

Or, if you're using PSR7 response :

try {
    // ... 
} catch (\Chiron\Http\Exception\HttpExceptionInterface $e) {
    $response = $response
        ->withStatus($e->getStatusCode())
        ->withHeader("Content-type", "text/html")
        ->getBody()->write("<h1>" . $e->getMessage() . "</h1>");
}

Api Problem

The following properties are available to use it for API Problem RFC 7807.

$e = new \Chiron\Http\Exception\Client\ForbiddenHttpException();

$e->setTitle('You do not have enough credit.');
$e->setDetail('Your current balance is 30, but that costs 50.');
$e->setType('https://example.com/probs/out-of-credit');
$e->setIntance('https://example.net/account/12345/msgs/abc');
$e->setAdditionalData(['balance' => 30, 'accounts' => ['https://example.net/account/12345', 'https://example.net/account/67890']]);

throw $e;

And output the API Problem response like this :

try {
    // ... 
} catch (\Chiron\Http\Exception\HttpException $e) {
    http_response_code($e->getStatusCode());
    header("Content-type: application/problem+json");
    print json_encode($e);
}

For XML output you can use the function $e->toArray() and serialize the data.

Install

Add Chiron/http-exceptions to your composer.json

{
    "require": {
        "chiron/http-exceptions": "^2.0"
    }
}

License

Licensed under the MIT license

Suggestions

Tips : Usage Suggestion