debuss-a/problem-details
最新稳定版本:1.0.2
Composer 安装命令:
composer require debuss-a/problem-details
包简介
An implementation of RFC 7807 - Problem Details for HTTP APIs
README 文档
README
An implementation of RFC 7807 - Problem Details for HTTP APIs.
This package provides a simple way to return standardized error responses that are both machine-readable and human-friendly.
Installation
composer require debuss-a/problem-details
Usage
Creating a Problem Details object
use ProblemDetails\ProblemDetails; $problem = new ProblemDetails( type: 'https://example.com/probs/out-of-credit', title: 'You do not have enough credit.', status: 403, detail: 'Your current balance is 30, but that costs 50.', instance: '/account/12345/msgs/abc', extensions: [ 'balance' => 30, 'accounts' => ['/account/12345', '/account/67890'] ] ); // JSON serialization $json = json_encode($problem);
Using the ProblemDetailsException
use ProblemDetails\ProblemDetailsException; try { // Your application logic if ($user->balance < $item->price) { $problem = new ProblemDetails( type: 'https://example.com/probs/out-of-credit', title: 'You do not have enough credit.', status: 403, detail: "Your current balance is {$user->balance}, but that costs {$item->price}." ); throw new ProblemDetailsException($problem); } } catch (ProblemDetailsException $e) { // Deal with the exception, or... // ...if set, the middleware will handle this automatically throw $e; }
Using the Middleware
Add the middleware to your middleware pipeline:
use Laminas\Diactoros\ResponseFactory; use ProblemDetails\ProblemDetailsMiddleware; // For PSR-15 compatible frameworks $response_factory = new ResponseFactory(); $app->add(new ProblemDetailsMiddleware($response_factory));
The middleware will:
- Catch any
ProblemDetailsException - Convert it to a proper Problem Details response
- Set appropriate Content-Type header (
application/problem+json)
About RFC 7807
RFC 7807 defines a standard format for returning error details from HTTP APIs.
It improves error handling by providing structured data that can be easily parsed by both machines and humans.
A Problem Details object includes:
type- A URI reference that identifies the problem typetitle- A short, human-readable summary of the problem typestatus- The HTTP status codedetail- A human-readable explanation specific to this occurrence of the probleminstance- A URI reference that identifies the specific occurrence of the problem
License
This package is released under the MIT License. See the LICENSE file for details.
统计信息
- 总下载量: 109
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-01