优化代码

main
gzydong 2021-07-16 22:15:49 +08:00
parent 8b96f05381
commit 2750469159
5 changed files with 55 additions and 3 deletions

View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Exception;
use Hyperf\Server\Exception\ServerException;
/**
* Class BaseException
*
* @package App\Exception
*/
class BaseException extends ServerException
{
}

View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Exception\Handler;
use App\Exception\BaseException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
/**
* Class BaseExceptionHandler
*
* @package App\Exception\Handler
*/
class BaseExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response)
{
// 格式化输出
$data = json_encode([
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
], JSON_UNESCAPED_UNICODE);
// 阻止异常冒泡
$this->stopPropagation();
return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(200)->withBody(new SwooleStream($data));
}
public function isValid(Throwable $throwable): bool
{
return $throwable instanceof BaseException;
}
}

View File

@ -21,7 +21,6 @@ class JwtAuthExceptionHandler extends ExceptionHandler
$data = json_encode([
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
'data' => []
], JSON_UNESCAPED_UNICODE);
// 阻止异常冒泡

View File

@ -27,7 +27,6 @@ class ValidateExceptionHandler extends ExceptionHandler
$data = json_encode([
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
'data' => []
], JSON_UNESCAPED_UNICODE);
// 阻止异常冒泡

View File

@ -15,6 +15,7 @@ return [
Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\JwtAuthExceptionHandler::class,
App\Exception\Handler\ValidateExceptionHandler::class,
App\Exception\Handler\BaseExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
],
'ws' => [