sinema/json-api-error-laravel

为 Laravel 格式化通用的 JSON API 错误

0.4 2024-03-13 13:39 UTC

This package is auto-updated.

Last update: 2024-09-13 14:47:23 UTC


README

规范

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

安装

composer require sinema/json-api-error-laravel

使用

在您的 Laravel 控制器中

<?php

namespace App\Http\Controllers;

use Sinemah\JsonApi\Error\Error;
use Sinemah\JsonApi\Error\Responses\Laravel;
use Illuminate\Http\JsonResponse;

class AnyController extends Controller
{
    public function show(): JsonResponse
    {
        return Laravel::get()->json(
            Error::fromArray(
                [
                    'status' => 404,
                    'source' => null,
                    'title' => 'Item not found',
                    'detail' => sprintf('Item %s not found', request('item_uuid')),
                ]
            ),
            404
        );
    }
}

响应

{
    "errors": [
        {
            "status": 404,
            "title": "Item not found",
            "detail": "Item bd11f048-8663-4d95-8c7a-02a5579b0682 not found in customer data"
        }
    ]
}

构建错误堆栈。

<?php

namespace App\Http\Controllers;

use Sinemah\JsonApi\Error\Error;
use Sinemah\JsonApi\Error\Responses\Laravel;
use Illuminate\Http\JsonResponse;

class AnyController extends Controller
{
    public function show(): JsonResponse
    {
        return Laravel::get()
            ->add(Error::fromArray(['status' => 500, 'code' => 'first_error']))
            ->add(Error::fromArray(['status' => 500, 'code' => 'second_error']))
            ->add(Error::fromArray(['status' => 500, 'code' => 'third_error']))
            ->json();
    }
}

响应

{
    "errors": [
        {
            "status": 500,
            "code": "first_error"
        },
        {
            "status": 500,
            "code": "second_error"
        },
        {
            "status": 500,
            "code": "third_error"
        }
    ]
}

Laravel 响应

您无需通过 json 方法传递状态码。状态码将从您推入包中的第一个错误中获取。

->json()

您也可以使用 json 方法覆盖状态码。

->json(null, 401)