Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: align error response status mapping (#18688)

YuTengjingcd70af2f8864
diff --git a/src/utils/errorResponse.test.ts b/src/utils/errorResponse.test.ts
index 7d41cafba16..e3af36921c7 100644
--- a/src/utils/errorResponse.test.ts
+++ b/src/utils/errorResponse.test.ts
@@ -1,10 +1,19 @@
import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { ERROR_CODE_SPECS } from '@lobechat/model-runtime/errors';
import { ChatErrorType } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { createErrorResponse } from './errorResponse';
describe('createErrorResponse', () => {
+ it.each(Object.values(ERROR_CODE_SPECS).filter((spec) => spec !== undefined))(
+ 'returns HTTP $httpStatus for the canonical $code error code',
+ ({ code, httpStatus }) => {
+ const response = createErrorResponse(code);
+ expect(response.status).toBe(httpStatus);
+ },
+ );
+
// 测试各种错误类型的状态码
it('returns a 401 status for NoOpenAIAPIKey error type', () => {
const errorType = ChatErrorType.NoOpenAIAPIKey;
@@ -14,14 +23,15 @@ describe('createErrorResponse', () => {
it('returns a 401 status for InvalidAccessCode error type', () => {
const errorType = ChatErrorType.InvalidAccessCode;
- const response = createErrorResponse(errorType as any);
+ const response = createErrorResponse(errorType);
expect(response.status).toBe(401);
});
// 测试包含Invalid的错误类型
it('returns a 401 status for Invalid error type', () => {
const errorType = 'InvalidTestError';
- const response = createErrorResponse(errorType as any);
+ // @ts-expect-error Intentionally verifies compatibility with legacy Invalid* error types.
+ const response = createErrorResponse(errorType);
expect(response.status).toBe(401);
});
@@ -49,6 +59,12 @@ describe('createErrorResponse', () => {
expect(response.status).toBe(429);
});
+ it('returns a 504 status for ProviderNetworkError error type', () => {
+ const errorType = AgentRuntimeErrorType.ProviderNetworkError;
+ const response = createErrorResponse(errorType);
+ expect(response.status).toBe(504);
+ });
+
it('returns a 400 status for ExceededContextWindow error type', () => {
const errorType = AgentRuntimeErrorType.ExceededContextWindow;
const response = createErrorResponse(errorType);
@@ -99,13 +115,13 @@ describe('createErrorResponse', () => {
});
});
- // 测试状态码不在200-599范围内的情况
- it('logs an error when the status code is not a number or not in the range of 200-599', () => {
- const errorType = 'Unknown Error';
- const consoleSpy = vi.spyOn(console, 'error');
- try {
- createErrorResponse(errorType as any);
- } catch (e) {}
+ it('falls back to HTTP 500 and logs when the error type is unknown', () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ // @ts-expect-error Intentionally verifies the runtime boundary against an invalid error type.
+ const response = createErrorResponse('Unknown Error');
+
+ expect(response.status).toBe(500);
expect(consoleSpy).toHaveBeenCalled();
consoleSpy.mockRestore();
});
@@ -113,7 +129,7 @@ describe('createErrorResponse', () => {
// 测试默认情况
it('returns the same error type as status for unknown error types', () => {
const errorType = 500; // 假设500是一个未知的错误类型
- const response = createErrorResponse(errorType as any);
+ const response = createErrorResponse(errorType);
expect(response.status).toBe(errorType);
});
diff --git a/src/utils/errorResponse.ts b/src/utils/errorResponse.ts
index a69cda41d59..a6509d9a64f 100644
--- a/src/utils/errorResponse.ts
+++ b/src/utils/errorResponse.ts
@@ -1,9 +1,7 @@
import { AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
-import {
- AgentRuntimeErrorType,
- type ILobeAgentRuntimeErrorType,
-} from '@lobechat/model-runtime/types/error';
-import { type ErrorResponse, type ErrorType } from '@lobechat/types';
+import { getErrorCodeSpec } from '@lobechat/model-runtime/errors';
+import type { ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime/types/error';
+import type { ErrorResponse, ErrorType } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
/**
@@ -13,84 +11,55 @@ import { ChatErrorType } from '@lobechat/types';
*/
const AUTH_REQUIRED_ERROR_TYPES = new Set<ErrorType>([ChatErrorType.Unauthorized]);
+/**
+ * Resolves canonical runtime specs before app-only fallbacks so codes such as
+ * InvalidRequestFormat keep their declared 400 instead of the legacy Invalid* 401.
+ */
const getStatus = (errorType: ILobeAgentRuntimeErrorType | ErrorType) => {
+ const spec = getErrorCodeSpec(typeof errorType === 'string' ? errorType : undefined);
+ if (spec) return spec.httpStatus;
+
// InvalidAccessCode / InvalidAzureAPIKey / InvalidOpenAIAPIKey / InvalidZhipuAPIKey ....
if (errorType.toString().includes('Invalid')) return 401;
switch (errorType) {
+ case ChatErrorType.NoOpenAIAPIKey: {
+ return 401;
+ }
+
case ChatErrorType.SubscriptionPlanLimit:
- case ChatErrorType.FreePlanLimit:
- case ChatErrorType.InsufficientBudgetForModel:
case ChatErrorType.WorkspaceFrozenByAdmin:
case ChatErrorType.WorkspaceFrozenByRiskControl:
case ChatErrorType.WorkspaceSubscriptionInactive: {
return 403;
}
- // TODO: Need to refactor to Invalid OpenAI API Key
- case AgentRuntimeErrorType.InvalidProviderAPIKey:
- case AgentRuntimeErrorType.NoOpenAIAPIKey: {
- return 401;
- }
-
- case AgentRuntimeErrorType.ExceededContextWindow:
- case AgentRuntimeErrorType.ExceededToolLimit:
case ChatErrorType.SubscriptionKeyMismatch:
- case ChatErrorType.SystemTimeNotMatchError:
- case ChatErrorType.LobeHubModelDeprecated: {
+ case ChatErrorType.SystemTimeNotMatchError: {
return 400;
}
-
- case AgentRuntimeErrorType.LocationNotSupportError: {
- return 403;
- }
-
- case AgentRuntimeErrorType.ModelNotFound: {
- return 404;
- }
-
- case AgentRuntimeErrorType.AccountDeactivated: {
- return 403;
- }
-
- case AgentRuntimeErrorType.InsufficientQuota:
- case AgentRuntimeErrorType.QuotaLimitReached: {
- return 429;
- }
-
- // define the 471~480 as provider error
- case AgentRuntimeErrorType.AgentRuntimeError: {
- return 470;
- }
-
- case AgentRuntimeErrorType.ProviderBizError:
- case AgentRuntimeErrorType.ProviderContentPolicyViolation: {
- return 471;
- }
-
- // all local provider connection error
- case AgentRuntimeErrorType.OllamaServiceUnavailable:
- case ChatErrorType.OllamaServiceUnavailable:
- case AgentRuntimeErrorType.OllamaBizError: {
- return 472;
- }
}
- return errorType as number;
+ return typeof errorType === 'number' ? errorType : undefined;
};
export const createErrorResponse = (
errorType: ErrorType | ILobeAgentRuntimeErrorType,
body?: any,
) => {
- const statusCode = getStatus(errorType);
+ const resolvedStatusCode = getStatus(errorType);
+ const isValidStatusCode =
+ typeof resolvedStatusCode === 'number' &&
+ resolvedStatusCode >= 200 &&
+ resolvedStatusCode <= 599;
+ const statusCode = isValidStatusCode ? resolvedStatusCode : 500;
const data: ErrorResponse = { body, errorType };
- if (typeof statusCode !== 'number' || statusCode < 200 || statusCode > 599) {
+ if (!isValidStatusCode) {
console.error(
- `current StatusCode: \`${statusCode}\` .`,
- 'Please go to `./src/app/api/errorResponse.ts` to defined the statusCode.',
+ `Unknown error type: \`${errorType}\`.`,
+ 'Falling back to HTTP 500. Define the status in the shared error code specs or app mapping.',
);
}