<?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;
}
}
<?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');
}
}