glance-project/error-handler

此软件包已被放弃,不再维护。作者建议使用glance-project/error-middleware软件包。

错误中间件

v0.2.0 2021-09-21 19:00 UTC

This package is auto-updated.

Last update: 2022-02-18 16:58:14 UTC


README

Error%20Handler.png?theme=light&pattern=architect&style=style_1&md=1&showWatermark=0&fontSize=100px&images=exclamation&widths=auto 一个兼容PSR-7和PSR-15的错误处理中间件

安装

使用Composer安装

composer require glance-project/error-handler

入门

错误处理器应该是您应用程序首先执行的中间件。在Slim中,最后注册的中间件首先执行。

$app = \Slim\App::create();

$logger = /* ... */;
$errorMiddleware = ErrorMiddleware::create();
$errorMiddleware->setLogger($logger); // Optional. Accepts any PSR-3 logger
$errorMiddleware->debugMode(true);    // Optional. Set to false on production
$errorMiddleware->useSentry();        // Optional. Sentry must be installed and configured

$app->add(/* other middleware */);
$app->add($errorMiddleware);

/* Register routes here */

$app->run();

如果错误处理器不是首先注册的中间件,前一个中间件抛出的异常将无法正确处理。

异常

初始化后,所有未捕获的异常都由这个库处理。

ErrorMiddleware的行为会根据异常的类型而有所不同。

BaseException

在开发应用程序时,有时希望中断一切并返回错误给用户。此库提供了一个BaseException,它封装了一个或多个错误。

Error遵循JSON API标准的部分内容,以下字段是可选的

  • 标题
  • 详细信息
  • 代码
  • HTTP状态
  • 来源
$errors = [
    new Error("Invalid email", "Email is bad formatted."),
    new Error(
        "Invalid password",
        "Password should contain at least 6 characters.",
        12345,
        400,
        new ErrorSource("user/password")
    ),
];

throw new BaseException(400, $errors);

上述代码在您的应用程序中会产生以下HTTP响应

状态:400

{
    "status": 400,
    "errors": [
        {
            "title": "Invalid email",
            "details": "Email is bad formatted."
        }
        {
            "title": "Invalid password",
            "details": "Password should contain at least 6 characters.",
            "code": 12345,
            "status": 400,
            "source": { "pointer": "user/password" }
        }
    ]
}

您也可以通过扩展BaseException来创建自定义异常。

其他异常

任何其他类型的未捕获异常将导致以下HTTP响应。

状态:500

{
    "errors": [
        {
            "status": 500,
            "title": "Internal Error",
            "detail": "An unexpected server error occurred."
        }
    ]
}

如果开启debugMode,将附加额外的调试信息到响应体中,例如文件、行、消息和跟踪。

使用Sentry

要将未知错误发送到Sentry,请安装并初始化sentry/sdk。有关在PHP上设置Sentry的更多信息,请参阅官方文档

composer require sentry/sdk
<?php

\Sentry\init([
    "dsn"         => getenv("SENTRY_DSN"),
    "environment" => getenv("ENVIRONMENT"),
]);

$app = \Slim\App::create();

$logger = /* ... */;

$errorMiddleware = ErrorMiddleware::create();
$errorMiddleware->useSentry();

$app->add(/* other middleware */);
$app->add($errorMiddleware);

// Register routes here...

$app->run();