承接 lcobucci/error-handling-middleware 相关项目开发

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

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

lcobucci/error-handling-middleware

Composer 安装命令:

composer require lcobucci/error-handling-middleware

包简介

A PSR-15 middleware compatible with RFC 7807

README 文档

README

Total Downloads Latest Stable Version Unstable Version

Build Status Code Coverage

Motivation

There are many PHP implementations for the RFC 7807, even providing PSR-15 middleware. However, most of them - if not all - mix content negotiation, logging, and formatting with error handling. Some even force you to throw specific types of exceptions in order for them to work.

I believe that those aren't the best design decisions and that we need more flexibility to solve this problem.

Installation

This package is available on Packagist, and we recommend you to install it using Composer:

composer require lcobucci/error-handling-middleware

Usage

In order to us this package you must add the middleware to your pipeline, configuring the desired behaviour (debug info strategy and status code extraction strategy).

Once this is set you'll be able to have your errors/exceptions converted into the correct HTTP responses.

Middleware position

This package provides two middleware for handling errors: error logging and error conversion.

They are designed to be used in the very beginning of the HTTP middleware pipeline, just after the content negotiation one:

<?php
use Lcobucci\ContentNegotiation\ContentTypeMiddleware;
use Lcobucci\ErrorHandling\ErrorConversionMiddleware;
use Lcobucci\ErrorHandling\ErrorLoggingMiddleware;

// In a Laminas Mezzio application, it would look like this:
$application->pipe(ContentTypeMiddleware::fromRecommendedSettings( /* ... */ )); // Very first middleware
$application->pipe(new ErrorConversionMiddleware( /* ... */ ));
$application->pipe(new ErrorLoggingMiddleware( /* ... */ ));

// all other middleware.

With that we'll be able to perform the logging and conversion in the correct order, delegating the content negotiation and formatting to ContentTypeMiddleware - using the configured formatters.

Important

The ErrorConversionMiddleware uses an UnformattedResponse to let the ContentTypeMiddleware perform the formatting. Make sure you have configured formatters for the MIME types application/problem+json and/or application/problem+xml.

It also makes the error/exception available in the error attribute of the response, so you may access it (if needed) by using another middleware between ErrorConversionMiddleware and ContentTypeMiddleware.

Configuring the conversion middleware behaviour

There're two extension points that you can use for that: debug info strategy and status code extraction strategy.

You can also configure the response body attributes by implementing certain interfaces in your exceptions.

Debug info strategy

This defines how the _debug property should be generated in the response body. We provide two default implementations - one designed for production mode and the other for development mode.

To configure this you must pass the desired implementation (or a customised one) as the second argument of the ErrorConversionMiddleware constructor.

To provide your own implementation you need to create a class that implements the DebugInfoStrategy interface.

Status code extraction strategy

This defines how the translation from error/exception to HTTP status code should be done. We provide a single default implementation for that, which is based on class maps.

To configure this you must pass the desired implementation (or a customised one) as the third argument of the ErrorConversionMiddleware constructor.

To provide your own implementation you need to create a class that implements the StatusCodeExtractionStrategy interface.

Default class map

The default map uses the marker interfaces in this packages to perform such translation. If the error/exception doesn't implement any of the marker interfaces, the error/exception code will be used (when it's different than zero), or fallback to the status code 500 (Internal Server Error).

The default map is:

  • Lcobucci\ErrorHandling\Problem\InvalidRequest -> 400
  • Lcobucci\ErrorHandling\Problem\AuthorizationRequired -> 401
  • Lcobucci\ErrorHandling\Problem\Forbidden -> 403
  • Lcobucci\ErrorHandling\Problem\ResourceNotFound -> 404
  • Lcobucci\ErrorHandling\Problem\Conflict -> 409
  • Lcobucci\ErrorHandling\Problem\ResourceNoLongerAvailable -> 410
  • Lcobucci\ErrorHandling\Problem\UnprocessableRequest -> 422
  • Lcobucci\ErrorHandling\Problem\ServiceUnavailable-> 503

This allows us to create our own exceptions that are automatically converted to the correct status code:

<?php
declare(strict_types=1);

namespace My\Fancy\App\UserManagement;

use Lcobucci\ErrorHandling\Problem\ResourceNotFound;
use RuntimeException;

final class UserNotFound extends RuntimeException implements ResourceNotFound
{
}

Important: you SHOULD NOT implement more than one of the marker interfaces, otherwise you may have unexpected results.

Customising the response body properties

With this library, you may modify the type and title properties of the generated response and also append new members to it.

That's done by implementing the Typed, Titled, and/or Detailed interfaces - you don't necessarily need to implement all of them, only the ones you want.

The example below shows how to represent one of the samples in the RFC 7807:

<?php
declare(strict_types=1);

namespace My\Fancy\App\UserManagement;

use Lcobucci\ErrorHandling\Problem\Forbidden;
use Lcobucci\ErrorHandling\Problem\Typed;
use Lcobucci\ErrorHandling\Problem\Titled;
use Lcobucci\ErrorHandling\Problem\Detailed;
use RuntimeException;
use function sprintf;

final class InsufficientCredit extends RuntimeException implements Forbidden, Typed, Titled, Detailed
{
    private $currentBalance;

    public static function forPurchase(int $currentBalance, int $cost): self
    {
        $exception = new self(sprintf('Your current balance is %d, but that costs %d.', $currentBalance, $cost));
        $exception->currentBalance = $currentBalance;

        return $exception;
    }

    public function getTypeUri(): string
    {
        return 'https://example.com/probs/out-of-credit';
    }

    public function getTitle(): string
    {
        return 'You do not have enough credit.';
    }

    /** @inheritDoc */
    public function getExtraDetails(): array
    {
        return ['balance' => $this->currentBalance]; // you might add "instance" and "accounts" too :)
    }
}

License

MIT, see LICENSE.

lcobucci/error-handling-middleware 适用场景与选型建议

lcobucci/error-handling-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 72.56k 次下载、GitHub Stars 达 61, 最近一次更新时间为 2019 年 06 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 lcobucci/error-handling-middleware 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 72.56k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 61
  • 点击次数: 32
  • 依赖项目数: 1
  • 推荐数: 1

GitHub 信息

  • Stars: 61
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-06-27