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;
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)));
}
// 交给下一个异常处理器