freepeace/larabone

个人Laravel扩展包,用于创建API

dev-master 2019-06-20 06:40 UTC

This package is auto-updated.

Last update: 2024-09-20 18:12:44 UTC


README

个人Laravel扩展包,用于创建API。

安装

您可以通过composer安装此包

composer require --prefer-dist freepeace/larabone

异常处理

包包含三个内置异常

  • NotFoundException (404)
  • ForbiddenException (403)
  • UnauthorizedException (401)

但您可以通过扩展 APIException 类自由创建您自己的异常。

示例

<?php

namespace App\Exceptions;

use Freepeace\Larabone\Exceptions\APIException;

class ServerErrorException extends APIException
{
    public function __construct(string $message = null, array $headers = [])
    {
        parent::__construct(500, $message, null, $headers);
    }
}

用法

20:     throw new \App\Exceptions\ServerErrorException('Oops! Something went wrong.');

上面的示例将返回以下JSON响应

# Debug = true
{
    "message": "Oops! Something went wrong",
    "debug": {
        "exception": "App\Exceptions\ServerErrorException",
        "file": "path-to-file-where-exception-is-thrown",
        "line":  20
    }
}
# Debug = false
{
    "message": "Oops! Something went wrong."
}

不要忘记 在异常处理器中调用 APIException::responder 函数。编辑您的 App\Exceptions\Handler 类中的 render 函数

<?php

namespace App\Exceptions;

use Freepace\Larabone\Exceptions\APIException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    public function render($request, Exception $exception)
    {
        if ($request->ajax()) {
            return APIException::responder($request, $exception);
        }

        return parent::render($request, $exception);
    }
}