phauthentic / error-response
0.1.1
2024-03-13 17:30 UTC
Requires
- php: ^8.1
- psr/http-factory: ^1.0
- psr/http-message: ^2.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- nyholm/psr7: ^1.8
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.5.0
- squizlabs/php_codesniffer: ^3.9
This package is auto-updated.
Last update: 2024-08-27 16:09:05 UTC
README
该库是 RFC 9457 的实现。
HTTP 状态码并不能总是传达足够的信息来帮助用户了解错误。虽然人类用户使用网页浏览器时通常可以理解 HTML 响应内容,但非人类用户在使用 HTTP API 时则很难做到。
为了解决这一不足,RFC 9457 定义了简单的 JSON 和 XML 文档格式来描述遇到的问题的具体细节。
例如,考虑一个指示客户端账户余额不足的响应。API 设计者可能会决定使用 403 禁止状态码来通知通用的 HTTP 软件(如客户端库、缓存和代理)响应的一般语义。API 特定的问题详情(如为什么服务器拒绝请求以及适用的账户余额)可以包含在响应内容中,以便客户端可以相应地操作(例如,触发将更多信用转移到账户中)。
HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
Content-Language: en
{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"detail": "Your current balance is 30, but that costs 50.",
"instance": "/account/12345/msgs/abc",
"balance": 30,
"accounts": ["/account/12345",
"/account/67890"]
}
安装
composer require phauthentic/error-response
文档
建议至少简要阅读 RFC 9457 以了解 RFC 以及实际的实现如何帮助您。
中间件
ErrorResponseMiddleware
是一个 PSR-15 中间件,用于处理在请求执行期间抛出的异常,并将它们转换为符合 RFC 9457 的错误响应。
中间件接受两个参数
- 实现
Psr\Http\Message\ResponseFactoryInterface
的 PSR7 响应工厂。 - 中间件应拦截的异常类名数组。如果异常是这些类中的任何一种的实例,它将被转换为错误响应。
$middleware = new ErrorResponseMiddleware( new Psr7ResponseFactory(), [ MyCustomException::class, OtherExceptionClass::class ] );
使用适当的类层次结构来处理您的异常!例如,从 DatabaseAccessLayerException
派生子类型,而不是声明数百个异常类并将它们传递给中间件。
错误响应
可以使用提供的工厂之一或直接实例化 ErrorResponse
来构建错误响应。
$this->errorResponseFactory->createJsonResponseFromError( new ErrorResponse( status: 403, type: 'https://example.com/probs/out-of-credit', title: 'You do not have enough credit.', extensions: [ 'balance' => 30, 'accounts' => [ "/account/12345", "/account/67890" ] ] ); );
许可证
版权所有 Florian Krämer
在 MIT 许可证 下发布。