封装优化
This commit is contained in:
42
extend/Aether/PHP/Hyperf/ApiExceptionHandler.php
Normal file
42
extend/Aether/PHP/Hyperf/ApiExceptionHandler.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Aether;
|
||||
|
||||
use function Hyperf\Support\env;
|
||||
use Hyperf\ExceptionHandler\ExceptionHandler;
|
||||
use Hyperf\HttpMessage\Stream\SwooleStream;
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Throwable;
|
||||
use Hyperf\Context\Context;
|
||||
|
||||
class ApiExceptionHandler extends ExceptionHandler
|
||||
{
|
||||
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
|
||||
{
|
||||
// 格式化输出
|
||||
$data = [
|
||||
'code' => $throwable->getCode() ?: 500,
|
||||
'message' => $throwable->getMessage() ?: '服务器内部错误',
|
||||
'request_id' => Context::get('request_id', ''),
|
||||
'timestamp' => time(),
|
||||
];
|
||||
|
||||
// 开发环境显示堆栈信息
|
||||
if (env('APP_ENV') === 'dev') {
|
||||
$data['trace'] = $throwable->getTraceAsString();
|
||||
}
|
||||
|
||||
$body = json_encode($data, JSON_UNESCAPED_UNICODE);
|
||||
return $response->withHeader('Content-Type', 'application/json')
|
||||
->withStatus($data['code'] >= 400 && $data['code'] < 500 ? $data['code'] : 500)
|
||||
->withBody(new SwooleStream($body));
|
||||
}
|
||||
|
||||
public function isValid(Throwable $throwable): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user