ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
> 异常的捕获机制为我们提供了便利的操作,使得业务层更加的清晰,比如以后要对某一个异常进行数据库存储,那么可以交给异常处理机制 [TOC] ## 创建异常类 ~~~ namespace App\Exception; use Hyperf\Server\Exception\ServerException; class FooException extends ServerException { } ~~~ ## 创建异常处理类 ~~~ namespace App\Exception\Handler; use Hyperf\ExceptionHandler\ExceptionHandler; use Hyperf\HttpMessage\Stream\SwooleStream; use Psr\Http\Message\ResponseInterface; use App\Exception\FooException; use Throwable; class FooExceptionHandler extends ExceptionHandler { public function handle(Throwable $throwable, ResponseInterface $response) { // 判断被捕获到的异常是希望被捕获的异常 if ($throwable instanceof FooException) { // 格式化输出 $data = json_encode([ 'code' => $throwable->getCode(), 'message' => $throwable->getMessage(), ], JSON_UNESCAPED_UNICODE); // 阻止异常冒泡 $this->stopPropagation(); return $response->withStatus(500)->withBody(new SwooleStream($data)); } // 交给下一个异常处理器 return $response; // 或者不做处理直接屏蔽异常 } /** * 判断该异常处理器是否要对该异常进行处理 */ public function isValid(Throwable $throwable): bool { //return $throwable instanceof FooException; return true; } } ~~~ ## 配置文件:注册异常处理类 > 配置文件:/config/autoload/exceptions.php ~~~ return [ 'handler' => [ // 这里的 http 对应 config/autoload/server.php 内的 server 所对应的 name 值 'http' => [ // 这里配置完整的类命名空间地址已完成对该异常处理器的注册 \App\Exception\Handler\FooExceptionHandler::class, ], ], ]; ~~~ ## controller中触发异常 ~~~ class IndexController extends AbstractController { public function index() { if (true) { throw new FooException('Foo Exception222...', 800); } $user = $this->request->input('user', 'Hyperf'); return [ 'message' => "Hello222 {$user}.", ]; } } ~~~