feat : exception

This commit is contained in:
2024-11-12 11:50:02 +08:00
parent 7fbce21622
commit 193b862977

View File

@@ -3,6 +3,7 @@
namespace App\Exception\Handler; namespace App\Exception\Handler;
use App\Lib\AdminReturn; use App\Lib\AdminReturn;
use App\Lib\ApiReturn;
use Hyperf\ExceptionHandler\ExceptionHandler; use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpServer\Request; use Hyperf\HttpServer\Request;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@@ -12,9 +13,16 @@ use Hyperf\HttpMessage\Stream\SwooleStream;
class ValidationDataExceptionHandler extends ExceptionHandler 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,31 +34,23 @@ class ValidationDataExceptionHandler extends ExceptionHandler
{ {
if ($throwable instanceof ValidationException) { if ($throwable instanceof ValidationException) {
// 格式化输出 // 格式化输出
$request = new Request(); $urlArr = explode('/',$this->request->path());
$url = $request->path();
$urlArr = explode('/',$url); $result = match ($urlArr[0]) {
'api' => $this->apiReturn->error($throwable->validator->errors()->first()),
if ($urlArr[0] == 'admin') { 'admin', 'common' => $this->adminReturn->error($throwable->validator->errors()->first()),
$result = $this->adminReturn->error($throwable->validator->errors()->first()); default => null,
}else{ };
//todo api
$result = $this->adminReturn->error($throwable->validator->errors()->first());
}
// 阻止异常冒泡 // 阻止异常冒泡
$this->stopPropagation(); $this->stopPropagation();
if (!is_array($result)){ if (!empty($result)) {
return $response->withHeader("Content-Type", "application/json")
->withStatus(200)
->withBody(new SwooleStream($result));
}
return $response->withHeader("Content-Type", "application/json") return $response->withHeader("Content-Type", "application/json")
->withStatus(200) ->withStatus(200)
->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE))); ->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE)));
} }
}
// 交给下一个异常处理器 // 交给下一个异常处理器
return $response; return $response;