kamranahmedse/laravel-faulty

一个用于在API中返回RESTful异常的最小化包。

1.1.1 2017-02-18 15:51 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:20:10 UTC


README

自动将抛出的异常(HTTP/非HTTP)转换为符合API问题规范的JSON响应。

一个让用户轻松处理API问题的Laravel/Lumen包。

Faulty提供了对IETF问题规范的直接实现,并将异常转换为以下格式返回,内容类型为application/problem+json

{
   "status": 403,
   "type": "http://example.com/problems/out-of-credit",
   "title": "You do not have enough credit.",
   "detail": "Your current balance is 30, but that costs 50.",
   "instance": "http://example.net/account/12345/logs?id=233"
}

其中

  • type 是标识问题类型的绝对URI
  • title 是问题的摘要
  • status 是状态码
  • detail 是针对问题的可读性解释
  • instance 是标识问题特定发生的绝对URI

安装

运行以下命令

composer require kamranahmedse/laravel-faulty

将你的异常处理器(例如App\Exceptions\Handler)扩展为位于app\Exceptions\Handler.php的Faulty处理器,如下所示:

use KamranAhmed\Faulty\Handler as FaultyHandler;

class Handler extends FaultyHandler {
   // ...
}

就这样。你已经准备好使用Faulty了。

## 配置 Faulty 依赖于以下环境配置

  • APP_DEBUG : 如果为true,异常将以whoops渲染,如果为false,则返回JSON。默认为false
  • APP_DEBUG_TRACE : 如果为true,将在应用程序错误中包含堆栈跟踪。默认为true

使用方法

为了正确渲染带有适当状态码的HTTP异常,你应该使用Faulty提供的异常类,即位于Faulty\Exceptions命名空间中的类,或者使用Symfony的HTTP组件提供的相关类,即位于Symfony\Component\HttpKernel\Exception下的类。

### 抛出异常

所有异常类都有以下签名

use KamranAhmed\Faulty\Exceptions\[ProblemType]Exception;
[ProblemType]Exception($detail, $title = '', $instance = '', $type = '')

以下是提供的一些异常类

// Include the exception classes from the given namespace

throw new BadRequestException('Invalid request data');
throw new ConflictException('Same request is already pending');
throw new ForbiddenException('You are not allowed to perform this action');
throw new InternalErrorException('Exports directory isn\'t writable');
throw new NoContentException('Deletion request successfuly accepted');
throw new NotFoundException('Item not found');
throw new NotModifiedException('..');
throw new PaymentRequiredException('..');
throw new PreconditionFailedException('..');
throw new ProcessingException('..');
throw new RequestTimeoutException('..');
throw new RequestTooLongException('..');
throw new UnauthorizedException('..');
throw new UnprocessableEntityException('..');

此外,如果你需要返回没有提供异常类的任何响应,可以使用HttpException类,如下所示:

use KamranAhmed\Faulty\Exceptions\HttpException;

throw new HttpException($title = '', $status = 500, $detail = '', $instance = '', $type = '');

语法糖

此外,对于上述任何异常类,你还可以使用以下语法。

$typeUrl = route('api.problem', ['type' => 'forbidden']);
$occurence = route('account.error', ['account_id' => 'A837332A', 'log_id' => 34]);

(new ForbiddenException("Your account doesn't have the balance of 50 USD"))
    ->setTitle('Balance too low)
    ->setType($problemRoute)
    ->setInstance($occurence)
    ->toss();

此外,如果你想在响应中发送额外的数据,请在错误对象上调用方法setAdditional([]),并传递额外的详细信息。

(new ForbiddenException("Your account doesn't have the balance of 50 USD"))
    ->setTitle('Balance too low)
    ->setAdditional([
        'current_balance' => 40,
        'required_balance' => 50,
        'item_detail' => $itemArray
    ])
    ->toss();

贡献

请随意分叉、增强、创建PR和锁定问题。

许可

MIT © Kamran Ahmed