一、通过 注解 注册异常处理器
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');
}
}