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');
    }
}
相关推荐
BingoGo19 小时前
PHP 如何利用 Opcache 来实现保护源码
后端·php
BingoGo2 天前
2025 年 PHP 常见面试题整理以及对应答案和代码示例
后端·php
Bruce1233 天前
web专题之php代审(二)
php
BingoGo3 天前
PHP-FPM 深度调优指南 告别 502 错误,让你的 PHP 应用飞起来
后端·php
亿坊电商3 天前
物联网领域中PHP框架的最佳选择有哪些?
物联网·struts·php
wuzuyu3653 天前
用php做一个简易的路由
php·路由
老六ip加速器4 天前
手机ip隔离方法
tcp/ip·智能手机·php
rockmelodies4 天前
【PHP7内核剖析】-1.3 FPM
php
真正的醒悟4 天前
上网管理行为-ISP路由部署
服务器·php·接口隔离原则
张晓~183399481214 天前
短视频矩阵源码-视频剪辑+AI智能体开发接入技术分享
c语言·c++·人工智能·矩阵·c#·php·音视频