- 在多个控制器中引入 ApiMessage,替换原有的 ApiResponse 错误处理逻辑,确保错误信息的一致性与可读性。 - 更新错误返回信息,使用更具语义的键值,提升 API 的可维护性与用户体验。 - 适配相关控制器的请求参数,确保在处理错误时能够正确返回相应的错误信息。
35 lines
979 B
PHP
35 lines
979 B
PHP
<?php
|
||
|
||
namespace App\Support;
|
||
|
||
use App\Lottery\ErrorCode;
|
||
use Illuminate\Http\JsonResponse;
|
||
use Illuminate\Http\Request;
|
||
|
||
/**
|
||
* 对外 API 统一 JSON 结构:{ code, msg, data }。
|
||
*
|
||
* - `code=0` 即 {@see ErrorCode::Success};非 0 见 `ErrorCode` 与 docs/04 §10。
|
||
* - error() 的 HTTP 状态可与 code 独立(如鉴权失败 401 + code 8001)。
|
||
*/
|
||
final class ApiResponse
|
||
{
|
||
public static function success(mixed $data = null, ?string $msg = null, int $code = 0, ?Request $request = null): JsonResponse
|
||
{
|
||
return response()->json([
|
||
'code' => $code,
|
||
'msg' => $msg ?? ApiMessage::successMessage($request),
|
||
'data' => $data,
|
||
]);
|
||
}
|
||
|
||
public static function error(string $msg, int $code, mixed $data = null, int $httpStatus = 400): JsonResponse
|
||
{
|
||
return response()->json([
|
||
'code' => $code,
|
||
'msg' => $msg,
|
||
'data' => $data,
|
||
], $httpStatus);
|
||
}
|
||
}
|