chiron/http-exceptions

Http异常类。

2.03 2020-10-04 12:46 UTC

This package is auto-updated.

Last update: 2024-09-18 18:03:18 UTC


README

Build Status Coverage Status CodeCov

Total Downloads Monthly Downloads

StyleCI PHP-Eye PHPStan

HttpExceptions

实现了RFC 7231中所有HTTP状态码的独立异常。

这些异常支持IETF为HTTP API定义的简单问题详细信息实现(RFC 7807)。

抽象的HttpException类及其子类提供了与HTTP错误状态码对应的异常。最常见的一些已经包括在内,但您可以通过使用(或扩展)HttpException并为$title提供原因短语以及$statusCode提供状态码来创建其他状态码的异常。

此包在Chiron\Http\Exception\Client命名空间中提供了以下异常类,用于4xx http错误。在Chiron\Http\Exception\Server命名空间中提供用于5xx http错误的异常类。

4xx:客户端错误 - 请求包含错误的语法或无法完成 5xx:服务器错误 - 服务器未能完成显然有效的请求

客户端错误

服务器错误

HTTP状态码参考

基本用法

抛出异常。

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

抛出一个带自定义消息的异常。

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

捕获异常并输出HTML响应。

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

或者,如果您使用PSR7响应

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

以下属性可用于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;

并且按照以下方式输出API Problem响应

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

对于XML输出,您可以使用函数$e->toArray()并序列化数据。

安装

Chiron/http-exceptions添加到您的composer.json中

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

许可证

MIT许可证下授权

建议

提示: 使用建议