10. 异常处理器

一、通过 注解 注册异常处理器

php 复制代码
<?php
namespace App\Exception\Handler;

use App\Exception\FooException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

use Hyperf\ExceptionHandler\Annotation\ExceptionHandler as RegisterHandler;

// Hyperf\ExceptionHandler\Annotation\ExceptionHandler 注解 取别名 RegisterHandler
#[RegisterHandler(server: 'http')]
class FooExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        echo '异常被执行了';
        return $response->withStatus(501)->withBody(new SwooleStream('This is FooExceptionHandler'));
    }

    public function isValid(Throwable $throwable): bool
    {
        // isValid为true时,执行 handle方法
        return $throwable instanceof FooException;
    }
}

二、通过配置文件注册异常处理器

定义配置文件

  • config/autoload/exception.php
php 复制代码
<?php

return [
    'handler' => [
        'http' => [
            App\Exception\Handler\FooExceptionHandler::class,	// 新增配置项
            Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
            App\Exception\Handler\AppExceptionHandler::class,
        ],
    ],
];

定义异常处理器

  • app/Exception/Handler/FooExceptionHandler
php 复制代码
<?php
namespace App\Exception\Handler;

use App\Exception\FooException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

class FooExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        $this->stopPropagation();	// 调用该方法,异常不再往后传递
        echo '异常被执行了';
        return $response->withStatus(501)->withBody(new SwooleStream('This is FooExceptionHandler'));
    }

    public function isValid(Throwable $throwable): bool
    {
        // isValid为true时,执行 handle方法
        return $throwable instanceof FooException;
    }
}

定义异常类

  • app/Exception/FooException
php 复制代码
<?php

namespace App\Exception;

class FooException extends \RuntimeException
{

}

三、触发异常(调用控制器方法)

php 复制代码
<?php

namespace App\Controller;

use App\Exception\FooException;
use Hyperf\HttpServer\Annotation\AutoController;

#[AutoController]
class TestController
{
    public function exception()
    {
        throw new FooException('test');
    }
}
相关推荐
微爱帮监所写信寄信4 小时前
微爱帮监狱寄信写信工具照片高清处理技术架构
开发语言·人工智能·网络协议·微信·php
天下皆白_唯我独黑6 小时前
php -S 启动项目访问路由报错处理
开发语言·php
梅羽落7 小时前
python武器化开发_01
开发语言·python·php
兮动人8 小时前
Fatal error: Uncaught think\exception\ErrorException: SourceGuardian Loade
android·php
catchadmin8 小时前
2026 年 PHP 开发者进阶 快速高效开发学习习惯
学习·php
Web极客码9 小时前
深入解析WordPress的functions.php文件及其高效使用方法
开发语言·php
catchadmin10 小时前
CatchAdmin 2025 年终总结 模块化架构的进化之路
架构·php·开源软件
微爱帮监所写信寄信10 小时前
微爱帮监狱寄信写信小程序PHP底层优化框架
java·开发语言·数据库·spring·微信·php·mybatis
小虎哥-技术博客19 小时前
ThinkPHP 5.x 到 8.x 行为扩展迁移指南
php