63 lines
1.7 KiB
PHP
63 lines
1.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
/**
|
|
* This file is part of Hyperf.
|
|
*
|
|
* @link https://www.hyperf.io
|
|
* @document https://hyperf.wiki
|
|
* @contact group@hyperf.io
|
|
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
|
|
*/
|
|
namespace App\Exception\Handler;
|
|
|
|
//use App\Exception\ValidationException;
|
|
use App\Constants\HttpEnumCode;
|
|
use Hyperf\Contract\StdoutLoggerInterface;
|
|
use Hyperf\ExceptionHandler\ExceptionHandler;
|
|
use Hyperf\HttpMessage\Stream\SwooleStream;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use \Hyperf\Validation\ValidationException;
|
|
use Throwable;
|
|
|
|
class ValidationExceptionHandler extends ExceptionHandler
|
|
{
|
|
/**
|
|
* @var StdoutLoggerInterface
|
|
*/
|
|
protected $logger;
|
|
|
|
public function __construct(StdoutLoggerInterface $logger)
|
|
{
|
|
$this->logger = $logger;
|
|
}
|
|
|
|
public function handle(Throwable $throwable, ResponseInterface $response)
|
|
{
|
|
// 判断被捕获到的异常是希望被捕获的异常
|
|
if ($throwable instanceof ValidationException) {
|
|
|
|
$body = $throwable->validator->errors()->first();
|
|
|
|
// 阻止异常冒泡
|
|
$this->stopPropagation();
|
|
|
|
// 格式化输出
|
|
$data = json_encode([
|
|
'data' => [],
|
|
'code' => HttpEnumCode::CLIENT_HTTP_ERROR,
|
|
'message' => $body,
|
|
], JSON_UNESCAPED_UNICODE);
|
|
|
|
return $response->withStatus($throwable->status)->withHeader('content-type', 'application/json; charset=utf-8')->withBody(new SwooleStream($data));
|
|
}
|
|
// 交给下一个异常处理器
|
|
return $response;
|
|
}
|
|
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return true;
|
|
}
|
|
}
|