This commit is contained in:
Aether
2025-09-25 10:01:34 +08:00
parent 0ca8d067c6
commit 3c89a01a81
4 changed files with 96 additions and 2 deletions

View File

@@ -6,6 +6,10 @@ namespace Aether;
class AetherResponse
{
public const SUCCESS = 0;
public const ERROR = 1;
/**
* 成功响应.
* @param null|mixed $data 数据
@@ -14,7 +18,7 @@ class AetherResponse
public static function success(mixed $data = null, string $message = '操作成功'): array
{
return [
'code' => 0,
'code' => self::SUCCESS,
'message' => $message,
'data' => $data,
'timestamp' => time(),
@@ -27,7 +31,7 @@ class AetherResponse
* @param string $message 错误消息
* @param null|mixed $data 附加数据
*/
public static function error(int $code, string $message = '', mixed $data = null): array
public static function error(string $message = '', int $code = self::ERROR, mixed $data = null): array
{
return [
'code' => $code,
@@ -37,6 +41,22 @@ class AetherResponse
];
}
public static function page($list, int $total, int $page, int $size): array
{
return [
'code' => self::SUCCESS,
'message' => 'success',
'data' => [
'list' => $list,
'page' => $page,
'size' => $size,
'total' => $total,
'pages' => (int) ceil($total / $size),
],
'timestamp' => time(),
];
}
/**
* 获取默认错误消息.
*/

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Aether;
use Aether\Exception\BusinessException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use function Hyperf\Support\env;
class GlobalExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface
{
// 处理业务异常
if ($throwable instanceof BusinessException) {
$data = [
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
'data' => null,
'timestamp' => time(),
];
} else {
// 记录未知错误日志
$this->logger->error(sprintf(
'Unknown error: %s %s in %s:%d',
$throwable->getMessage(),
$throwable->getCode(),
$throwable->getFile(),
$throwable->getLine()
));
$data = [
'code' => 500,
'message' => 'Server internal error',
'data' => env('APP_ENV') === 'dev' ? [
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTraceAsString(),
] : null,
'timestamp' => time(),
];
}
$body = json_encode($data, JSON_UNESCAPED_UNICODE);
return $response->withHeader('Content-Type', 'application/json')
->withBody(new SwooleStream($body));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}