sinema/json-api-error

格式化通用的JSON:API错误

0.8 2024-03-13 13:40 UTC

This package is auto-updated.

Last update: 2024-09-13 15:02:55 UTC


README

规范

https://jsonapi.fullstack.org.cn/examples/#error-objects-basics

安装

composer require sinema/json-api-error

用法

基本用法

<?php

use Sinemah\JsonApi\Error\Error;
use Sinemah\JsonApi\Error\ErrorBag;

$errors = new ErrorBag();

$errors->add(
    Error::fromArray(
        [
            'status' => 404,
            'source' => null,
            'title' => 'Item not found',
            'detail' => sprintf('Item %s not found', 'some-id'),
        ]
    )
);

$errors->toArray()

JSON表示形式的结果

[
  {
    "status": 404,
    "title": "Item not found",
    "detail": "Item some-id not found"
  }
]

响应用法

<?php

use Sinemah\JsonApi\Error\Error;
use Sinemah\JsonApi\Error\Response;

$response = Response::get();

$response->add(
    Error::fromArray(
        [
            'status' => 404,
            'source' => null,
            'title' => 'Item not found',
            'detail' => sprintf('Item %s not found', 'some-id'),
        ]
    )
);

$response->toArray()

JSON表示形式的结果

{
    "errors": [
        {
            "status": 404,
            "title": "Item not found",
            "detail": "Item some-id not found"
        }
    ]
}