重新设计状态码规范

This commit is contained in:
2026-03-05 13:44:56 +08:00
parent 8d8cee696f
commit 5ab16243bd
6 changed files with 46 additions and 33 deletions

View File

@@ -37,23 +37,23 @@ class CheckAuthTokenMiddleware implements MiddlewareInterface
$token = $this->getAuthTokenFromRequest($request);
if ($token === '') {
throw new ApiException('请携带 auth-token', ReturnCode::MISSING_TOKEN);
throw new ApiException('请携带 auth-token', ReturnCode::UNAUTHORIZED);
}
if (!$this->looksLikeJwt($token)) {
throw new ApiException('auth-token 格式无效', ReturnCode::TOKEN_TIMEOUT);
throw new ApiException('auth-token 格式无效', ReturnCode::TOKEN_INVALID);
}
$decoded = $this->verifyAuthToken($token);
$extend = $decoded['extend'] ?? [];
if (($extend['plat'] ?? '') !== 'api') {
throw new ApiException('auth-token 无效(非 API 凭证)', ReturnCode::TOKEN_TIMEOUT);
throw new ApiException('auth-token 无效(非 API 凭证)', ReturnCode::TOKEN_INVALID);
}
// 同一设备只允许一个 auth-token 生效,非当前 token 视为已失效
$device = (string) ($extend['device'] ?? '');
if ($device !== '' && !AuthTokenCache::isCurrentToken($device, $token)) {
throw new ApiException('auth-token 已失效(该设备已签发新凭证,请使用新 auth-token', ReturnCode::TOKEN_TIMEOUT);
throw new ApiException('auth-token 已失效(该设备已签发新凭证,请使用新 auth-token', ReturnCode::TOKEN_INVALID);
}
return $handler($request);
@@ -87,13 +87,13 @@ class CheckAuthTokenMiddleware implements MiddlewareInterface
return JwtToken::verify(1, $token);
} catch (JwtTokenExpiredException $e) {
Log::error('auth-token 已过期, 报错信息' . $e);
throw new ApiException('auth-token 已过期', ReturnCode::TOKEN_TIMEOUT);
throw new ApiException('auth-token 已过期', ReturnCode::TOKEN_INVALID);
} catch (JwtTokenException $e) {
Log::error('auth-token 无效, 报错信息' . $e);
throw new ApiException($e->getMessage() ?: 'auth-token 无效', ReturnCode::TOKEN_TIMEOUT);
throw new ApiException($e->getMessage() ?: 'auth-token 无效', ReturnCode::TOKEN_INVALID);
} catch (\Throwable $e) {
Log::error('auth-token 校验失败, 报错信息' . $e);
throw new ApiException('auth-token 校验失败', ReturnCode::TOKEN_TIMEOUT);
throw new ApiException('auth-token 校验失败', ReturnCode::TOKEN_INVALID);
}
}