承接 sfelix-martins/json-exception-handler 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sfelix-martins/json-exception-handler

Composer 安装命令:

composer require sfelix-martins/json-exception-handler

包简介

Adds more power to Laravel Exceptions Handler to treat json responses

README 文档

README

StyleCI Scrutinizer Code Quality Build Status

Adds methods to your App\Exceptions\Handler to treat json responses. It is most useful if you are building APIs!

Requirements

  • Laravel Framework >= 5.4
  • php >= 7.0

JsonAPI

Using JsonAPI standard to responses!

Features

Default error response:

{
  "errors": [
    {
      "status": "404",
      "code": "13",
      "title": "model_not_found_exception",
      "detail": "User not found",
      "source": {
        "pointer": "data/id"
      }
    }
  ]
}

To Illuminate\Validation\ValidationException:

{
  "errors": [
    {
      "status": "422",
      "code": "1411",
      "title": "Required validation failed on field name",
      "detail": "The name field is required.",
      "source": {
        "pointer": "name"
      }
    },
    {
      "status": "422",
      "code": "1421",
      "title": "Email validation failed on field email",
      "detail": "The email must be a valid email address.",
      "source": {
        "pointer": "email"
      }
    }
  ]
}

Treated Exceptions

  • Illuminate\Auth\Access\AuthorizationException
  • Illuminate\Auth\AuthenticationException
  • Illuminate\Database\Eloquent\ModelNotFoundException
  • Illuminate\Validation\ValidationException
  • Laravel\Passport\Exceptions\MissingScopeException
  • League\OAuth2\Server\Exception\OAuthServerException
  • Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  • Symfony\Component\HttpKernel\Exception\BadRequestHttpException

Installing and configuring

Install the package

$ composer require sfelix-martins/json-exception-handler

If you are not using Laravel 5.5 version add the JsonHandlerServiceProvider to your config/app.php providers array:

    'providers' => [
        ...
        SMartins\Exceptions\JsonHandlerServiceProvider::class,
    ],

Publish the config to set your own exception codes

$ php artisan vendor:publish --provider="SMartins\JsonHandler\JsonHandlerServiceProvider"

Set your exception codes on config/json-exception-handler.php on codes array.

You can add more fields and codes to validation_fields array.

You can add too your models on lang packages to return the Not Found response translated correctly.

In resources/lang/vendor/exception/lang/$locale in exceptions file you can set on models array. Example:

    'models' => [
        'User' => 'Usuário',
        'Article' => 'Artigo',
    ]

Using

Use the trait on your App\Exception\Handler and add method jsonResponse() passing the $exception if $request expects a json response on render()method

use SMartins\Exceptions\JsonHandler;

class Handler extends ExceptionHandler
{
    use JsonHandler;

    // ...

    public function render($request, Exception $exception)
    {   
        if ($request->expectsJson()) {
            return $this->jsonResponse($exception);
        }

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

Use sample

class UserController extends Controller
{
    // ...

    public function store(Request $request)
    {
        // Validation
        $request->validate($this->rules);

        // or
        $this->validate($request, $this->rules);

        //and or
        Validator::make($request->all(), $this->rules)->validate();

        if (condition()) {
            // Generate response with http code and message
            abort(403, 'Action forbidden!');
        }

        if (anotherCondition()) {
            // Generate response with message and code
            throw new TokenMismatchException("Error Processing Request", 10);
        }
    }

    public function show($id)
    {
        // If not found the default response is called
        $user = User::findOrFail($id);
        
        // Gate define on AuthServiceProvider
        // Generate an AuthorizationException if fail
        $this->authorize('users.view', $user->id);
    }

Extending

You can too create your own handler to any Exception. E.g.:

  • Create a Handler class that extends of AbstractHandler:
namespace App\Exceptions;

use GuzzleHttp\Exception\ClientException;
use SMartins\Exceptions\Handlers\AbstractHandler;

class GuzzleClientHandler extends AbstractHandler
{
    /**
     * Create instance using the Exception to be handled.
     *
     * @param \GuzzleHttp\Exception\ClientException $e
     */
    public function __construct(ClientException $e)
    {
        parent::__construct($e);
    }
}
  • You must implements the method handle() from AbstractHandler class. The method must return an instance of Error or ErrorCollection:
namespace App\Exceptions;

use SMartins\Exceptions\JsonAPI\Error;
use SMartins\Exceptions\JsonAPI\Source;
use GuzzleHttp\Exception\ClientException;
use SMartins\Exceptions\Handlers\AbstractHandler;

class GuzzleClientHandler extends AbstractHandler
{
    // ...

    public function handle()
    {
        return (new Error)->setStatus($this->getStatusCode())
            ->setCode($this->getCode())
            ->setSource((new Source())->setPointer($this->getDefaultPointer()))
            ->setTitle($this->getDefaultTitle())
            ->setDetail($this->exception->getMessage());
    }

    public function getCode()
    {
        // You can add a new type of code on `config/json-exception-handlers.php`
        return config('json-exception-handler.codes.client.default');
    }
}
namespace App\Exceptions;

use SMartins\Exceptions\JsonAPI\Error;
use SMartins\Exceptions\JsonAPI\Source;
use SMartins\Exceptions\JsonAPI\ErrorCollection;
use SMartins\Exceptions\Handlers\AbstractHandler;

class MyCustomizedHandler extends AbstractHandler
{
    public function __construct(MyCustomizedException $e)
    {
        parent::__construct($e);
    }

    public function handle()
    {
        $errors = (new ErrorCollection)->setStatusCode(400);

        $exceptions = $this->exception->getExceptions();

        foreach ($exceptions as $exception) {
            $error = (new Error)->setStatus(422)
                ->setSource((new Source())->setPointer($this->getDefaultPointer()))
                ->setTitle($this->getDefaultTitle())
                ->setDetail($exception->getMessage());

            $errors->push($error);
        }

        return $errors;
    }
}
  • Now just registry your customized handler on App\Exception\Handler file on attribute exceptionHandlers. E.g:
namespace App\Exceptions;

use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use SMartins\Exceptions\JsonHandler;

class Handler extends ExceptionHandler
{
    use JsonHandler;

    protected $exceptionHandlers = [
        // Set on key the exception and on value the handler.
        ClientException::class => GuzzleClientHandler::class,
    ];

Response References:

sfelix-martins/json-exception-handler 适用场景与选型建议

sfelix-martins/json-exception-handler 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 65.4k 次下载、GitHub Stars 达 17, 最近一次更新时间为 2017 年 08 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「exceptions」 「api」 「laravel」 「handler」 「jsonapi」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sfelix-martins/json-exception-handler 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sfelix-martins/json-exception-handler 我们能提供哪些服务?
定制开发 / 二次开发

基于 sfelix-martins/json-exception-handler 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 65.4k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 17
  • 点击次数: 11
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 17
  • Watchers: 0
  • Forks: 15
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-08-27