Search by

fiberphp / exception

fiberphp

🛡️ FiberPHP 异常处理 —— ExceptionHandler 接口、框架异常基类、默认 Handler 实现,支持 HTTP/Console/RPC 三种上下文渲染。

v0.1.0 2026-11-22 14:13 UTC

This package is auto-updated.

Last update: 2026-11-22 14:14:47 UTC


README

异常处理基础包:ExceptionHandler 接口、框架异常基类 Exception 与默认 Handler,统一 HTTP / Console / RPC 三种上下文的上报与渲染。

环境要求

  • PHP >= 8.5
  • workerman/workerman ^5.2(HTTP 上下文返回 Workerman Response)
  • psr/log ^3.0
  • fiberphp/config、fiberphp/container、fiberphp/context

安装

composer require fiberphp/exception

快速上手

use FiberPHP\Exception\Handler;
use Throwable;

try {
    // 业务代码
} catch (Throwable $e) {
    $response = Handler::resolve()->handle($e, 'http');
}

Handler::resolve(array $constructorArgs = []): self 依次尝试应用定义的 App\ExceptionHandler 与内置 HTTP 渲染子类(存在时),最终回退默认 Handler;候选类未继承 FiberPHP\Exception\Handler 时跳过。

handle() 等价于 report() + render(),第二个参数决定返回结构:

context返回
httpWorkerman\Protocols\Http\Response(JSON)
console字符串(debug 模式附带调用栈)
rpc标准化错误数组

也可以分步调用:

$handler = new Handler($logger, $debug);  // 两个参数均可选

$handler->report($e, 'console');
$result = $handler->render($e, 'console');

Handler 构造签名为 __construct(?LoggerInterface $logger = null, ?bool $debug = null);省略时日志器从容器解析,debug 读取 app.debug 配置。

自定义异常

业务异常继承 FiberPHP\Exception\Exception,通过属性声明 HTTP 状态码与消息透出策略:

use FiberPHP\Exception\Exception;

final class NotFoundException extends Exception
{
    protected int $httpCode = 404;

    protected bool $messageSafe = true;
}
throw (new NotFoundException('资源不存在'))->withContext(['id' => 1]);
属性说明默认值
$httpCode对应的 HTTP 状态码500
$messageSafe非 debug 模式下消息是否透传给客户端false
$debugAwareboot 渲染是否附带 file / line / tracefalse

基类方法:

  • __construct(string $message = '', int $code = 1, ?Throwable $previous = null):$code 是业务错误码,与 HTTP 状态码无关。
  • setData(string $key, mixed $value): void、withContext(array $context): static、getData(): array:附加与读取调试数据。
  • getHttpCode(): int、isMessageSafe(): bool、isDebugAware(): bool:读取上述策略。
  • renderForBoot(): string:不依赖 Request 的 JSON 字符串(code / msg,debug 模式下附调试字段与 data),用于启动阶段与 CLI;app.debug 关闭时不输出调试信息。

自定义 ExceptionHandler

在应用中定义 App\ExceptionHandler 继承默认 Handler,按需覆盖上报策略与渲染逻辑:

namespace App;

use App\Exception\NotFoundException;
use FiberPHP\Exception\Handler;
use Psr\Log\LogLevel;

class ExceptionHandler extends Handler
{
    /** @var list<class-string> */
    protected array $dontReport = [NotFoundException::class];

    /** @var array<class-string, string> */
    protected array $levels = [NotFoundException::class => LogLevel::WARNING];
}
  • $dontReport 命中的异常跳过日志上报。
  • $levels 按异常类型声明日志级别,未命中时使用 error。
  • 需完全接管渲染时可覆盖 render(),需调整上报判定时可覆盖 shouldReport()。

运行期也可注册回调:

$handler->renderable(static function (Throwable $e, string $context): mixed {
    return $e instanceof NotFoundException ? ['code' => 404, 'msg' => 'not found'] : null;
});

$handler->reportable(static function (Throwable $e, string $context): void {
    // 上报到监控系统
});
  • renderable(Closure $callback): static:返回非 null 时短路默认渲染。
  • reportable(Closure $callback): static:回调返回 false 时跳过默认日志上报。

方法约定

异常类不必继承本包 Exception,实现以下方法即可参与默认渲染:

方法作用
getHttpCode(): intHTTP 状态码,未实现时兜底 500
isMessageSafe(): bool非 debug 模式下是否透传消息,未实现时统一返回通用文案
getData(): arraydebug 模式下附加到响应的调试数据
getErrors(): array附加到响应的字段错误列表
getHeaders(): array附加到 HTTP 响应头

测试

composer test

与其它包的关系

  • fiberphp/http 的 FiberPHP\Http\Exception\Handler 继承本包 Handler,补充 HTTP 渲染。
  • fiberphp/framework 在 Kernel 注册全局异常处理器,并按约定解析 App\ExceptionHandler。
  • 配置、容器与上下文能力分别来自 fiberphp/config、fiberphp/container、fiberphp/context。

License

MIT