fix: report resource conflicts and accurate CLI API errors

This commit is contained in:
whyour
2026-10-01 11:26:40 +08:00
parent a5406bedca
commit 06c8d8b112
7 changed files with 199 additions and 29 deletions
+52 -28
View File
@@ -53,23 +53,12 @@ export async function request(
// Check HTTP status before decoding (proxies may return HTML on denial).
if (!response.ok) {
await response.body?.cancel();
const suffix =
method !== 'GET' && response.status >= 500
? translate(
process.env,
' 执行结果可能未知,请先检查%s状态再考虑重试。',
resource,
)
: '';
fail(
translate(
process.env,
'API 请求被拒绝(HTTP %s),请检查%s。%s',
response.status,
credentialsHint,
suffix,
),
[401, 403].includes(response.status) ? 3 : 1,
rejectResponse(
response.status,
'HTTP',
method,
resource,
credentialsHint,
);
}
if (
@@ -100,28 +89,63 @@ export async function request(
),
);
}
if (endpoint.split('?')[0] === 'user/login' && isRecord(result) && result.code === 420)
fail(translate(process.env, '需要双因素验证,请调用 user two-factor-login。'), 3);
if (
endpoint.split('?')[0] === 'user/login' &&
isRecord(result) &&
result.code === 420
)
fail(
translate(process.env, '需要双因素验证,请调用 user two-factor-login。'),
3,
);
if (!isRecord(result) || result.code !== 200) {
const status =
isRecord(result) && typeof result.code === 'number'
? result.code
: undefined;
fail(
translate(
process.env,
'API 请求被拒绝(code %s),请检查%s。',
status ?? translate(process.env, '未知'),
credentialsHint,
),
status === 401 || status === 403 ? 3 : 1,
);
rejectResponse(status, 'code', method, resource, credentialsHint);
}
if (options.output)
fail(translate(process.env, '接口返回 JSON,未保存下载文件。'));
return result;
}
function rejectResponse(
status: number | undefined,
kind: 'HTTP' | 'code',
method: string,
resource: string,
credentialsHint: string,
): never {
const denied = status === 401 || status === 403;
const reason = denied
? translate(process.env, '请检查%s。', credentialsHint)
: status === 409
? translate(process.env, '资源冲突,请检查重复的名称或值。')
: status !== undefined && status >= 500
? translate(process.env, '服务端错误,请检查服务状态和日志。')
: translate(process.env, '请求未成功,请检查请求参数和服务日志。');
const suffix =
method !== 'GET' && (status === undefined || status >= 500)
? translate(
process.env,
' 执行结果可能未知,请先检查%s状态再考虑重试。',
resource,
)
: '';
fail(
translate(
process.env,
'API 请求失败(%s %s)。%s%s',
kind,
status ?? translate(process.env, '未知'),
reason,
suffix,
),
denied ? 3 : 1,
);
}
export async function authenticate(config: Credentials): Promise<Session> {
const query = new URLSearchParams({
client_id: config.clientId,
+6
View File
@@ -151,6 +151,12 @@ export const english: Record<string, string> = {
应用凭据: 'application credentials',
'应用凭据和 %s 权限': 'application credentials and %s permission',
未知: 'unknown',
'请检查%s。': 'Check %s.',
'资源冲突,请检查重复的名称或值。': 'Resource conflict; check for duplicate names or values.',
'服务端错误,请检查服务状态和日志。': 'Server error; check service status and logs.',
'请求未成功,请检查请求参数和服务日志。': 'Request unsuccessful; check request parameters and service logs.',
'API 请求失败(%s %s)。%s%s': 'API request failed (%s %s). %s%s',
' 执行结果可能未知,请先检查%s状态再考虑重试。':
' Execution outcome may be unknown; check %s status before retrying.',
'API 请求被拒绝(HTTP %s),请检查%s。%s':
+52 -1
View File
@@ -54,7 +54,7 @@ test('API diagnostics preserve resource scope, uncertainty, codes and secret sup
language === 'en' ? /outcome.*unknown/ : /结果.*未知/,
);
}
if (failure !== 'network') {
if (failure === 'permission' || failure === 'api') {
assert.ok(
error.message.includes(
endpoint.startsWith('subscriptions')
@@ -89,3 +89,54 @@ test('API diagnostics preserve resource scope, uncertainty, codes and secret sup
);
}
});
test('HTTP and body errors distinguish conflicts, authentication and server failures without leaking bodies', async (t) => {
const previous = process.env.QL_LANG;
t.after(() => {
if (previous === undefined) delete process.env.QL_LANG;
else process.env.QL_LANG = previous;
});
for (const language of ['en', 'zh']) {
process.env.QL_LANG = language;
for (const kind of ['HTTP', 'code'])
for (const status of [400, 401, 403, 409, 500, 503])
for (const method of ['GET', 'PUT']) {
t.mock.method(
global,
'fetch',
async () =>
new Response(
JSON.stringify({ code: status, message: 'secret-value' }),
{ status: kind === 'HTTP' ? status : 200 },
),
);
await assert.rejects(
request(
{ url: 'https://fixture.invalid', token: 'secret-token' },
'envs',
{ method },
),
(error) => {
assert.equal(error.exitCode, [401, 403].includes(status) ? 3 : 1);
assert.match(error.message, new RegExp(`${kind} ${status}`));
assert.doesNotMatch(error.message, /secret-|fixture/);
if ([401, 403].includes(status))
assert.match(error.message, /credentials|凭据/);
else
assert.doesNotMatch(
error.message,
/credentials|permission|凭据|权限/,
);
if (status === 409) assert.match(error.message, /conflict|冲突/);
if (status >= 500)
assert.match(error.message, /Server error|服务端错误/);
if (status >= 500 && method === 'PUT')
assert.match(error.message, /unknown|未知/);
else assert.doesNotMatch(error.message, /unknown|未知/);
return true;
},
);
t.mock.restoreAll();
}
}
});