一、通过 注解 注册异常处理器
<?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;
#[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{return $throwable instanceof FooException;}
}
二、通过配置文件注册异常处理器
定义配置文件
- config/autoload/exception.php
<?phpreturn ['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{return $throwable instanceof FooException;}
}
定义异常类
- app/Exception/FooException
<?phpnamespace App\Exception;class FooException extends \RuntimeException
{}
三、触发异常(调用控制器方法)
<?phpnamespace App\Controller;use App\Exception\FooException;
use Hyperf\HttpServer\Annotation\AutoController;#[AutoController]
class TestController
{public function exception(){throw new FooException('test');}
}