From 193b862977ec77b3ac73f31bb8b2097ee1c935de Mon Sep 17 00:00:00 2001 From: ctexthuang Date: Tue, 12 Nov 2024 11:50:02 +0800 Subject: [PATCH] feat : exception --- .../ValidationDataExceptionHandler.php | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/app/Exception/Handler/ValidationDataExceptionHandler.php b/app/Exception/Handler/ValidationDataExceptionHandler.php index dfdcffb..7a9cc9d 100644 --- a/app/Exception/Handler/ValidationDataExceptionHandler.php +++ b/app/Exception/Handler/ValidationDataExceptionHandler.php @@ -3,6 +3,7 @@ namespace App\Exception\Handler; use App\Lib\AdminReturn; +use App\Lib\ApiReturn; use Hyperf\ExceptionHandler\ExceptionHandler; use Hyperf\HttpServer\Request; use Psr\Http\Message\ResponseInterface; @@ -12,9 +13,16 @@ use Hyperf\HttpMessage\Stream\SwooleStream; class ValidationDataExceptionHandler extends ExceptionHandler { - public function __construct(protected AdminReturn $adminReturn) - { - } + /** + * @param Request $request + * @param AdminReturn $adminReturn + * @param ApiReturn $apiReturn + */ + public function __construct( + private readonly Request $request, + private readonly AdminReturn $adminReturn, + private readonly ApiReturn $apiReturn, + ) {} /** * 验证器异常处理 @@ -26,30 +34,22 @@ class ValidationDataExceptionHandler extends ExceptionHandler { if ($throwable instanceof ValidationException) { // 格式化输出 - $request = new Request(); - $url = $request->path(); + $urlArr = explode('/',$this->request->path()); - $urlArr = explode('/',$url); - - if ($urlArr[0] == 'admin') { - $result = $this->adminReturn->error($throwable->validator->errors()->first()); - }else{ - //todo api - $result = $this->adminReturn->error($throwable->validator->errors()->first()); - } + $result = match ($urlArr[0]) { + 'api' => $this->apiReturn->error($throwable->validator->errors()->first()), + 'admin', 'common' => $this->adminReturn->error($throwable->validator->errors()->first()), + default => null, + }; // 阻止异常冒泡 $this->stopPropagation(); - if (!is_array($result)){ + if (!empty($result)) { return $response->withHeader("Content-Type", "application/json") ->withStatus(200) - ->withBody(new SwooleStream($result)); + ->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE))); } - - return $response->withHeader("Content-Type", "application/json") - ->withStatus(200) - ->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE))); } // 交给下一个异常处理器