> 異常的捕獲機制為我們提供了便利的操作,使得業務層更加的清晰,比如以后要對某一個異常進行數據庫存儲,那么可以交給異常處理機制
[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}.",
];
}
}
~~~