10. 异常处理器

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

<?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

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

定义异常处理器

  • app/Exception/Handler/FooExceptionHandler
<?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

namespace App\Exception;

class FooException extends \RuntimeException
{

}

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

<?php

namespace App\Controller;

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

#[AutoController]
class TestController
{
    public function exception()
    {
        throw new FooException('test');
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值