欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 10. 异常处理器

10. 异常处理器

2024/10/28 3:31:33 来源:https://blog.csdn.net/weixin_42457618/article/details/143136817  浏览:    关键词: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
<?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{// isValid为true时,执行 handle方法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');}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com