SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix(api): guard ErrorResponseHandlerV2 against non-envelope error bodies (#12209)
Ashwin Bhatkalb4b8a9fda067
diff --git a/frontend/src/api/ErrorResponseHandlerForGeneratedAPIs.ts b/frontend/src/api/ErrorResponseHandlerForGeneratedAPIs.tsindex e015aff75c..c0d10e2bcd 100644--- a/frontend/src/api/ErrorResponseHandlerForGeneratedAPIs.ts+++ b/frontend/src/api/ErrorResponseHandlerForGeneratedAPIs.ts@@ -2,6 +2,29 @@ import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';import { AxiosError } from 'axios';import APIError from 'types/api/error';+// The wire shape these handlers can actually rely on. The generated+// RenderErrorResponseDTO marks code/message/url/errors as required, but the+// server omits any of them even on valid errors (e.g. a 400 with just a+// message), so a present `error` object is all the guard can guarantee.+type ErrorEnvelope = {+ error: {+ code?: string;+ message?: string;+ url?: string;+ errors?: { message?: string }[];+ };+};++function isErrorEnvelope(data: unknown): data is ErrorEnvelope {+ return (+ typeof data === 'object' &&+ data !== null &&+ 'error' in data &&+ typeof (data as ErrorEnvelope).error === 'object' &&+ (data as ErrorEnvelope).error !== null+ );+}+// @deprecated Use convertToApiError insteadexport function ErrorResponseHandlerForGeneratedAPIs(error: AxiosError<RenderErrorResponseDTO>,@@ -10,15 +33,29 @@ export function ErrorResponseHandlerForGeneratedAPIs(// The request was made and the server responded with a status code// that falls out of the range of 2xxif (response) {+ // The body isn't guaranteed to be an error envelope — e.g. a gateway 5xx+ // with an HTML/empty body during a deploy. Verify the shape before reading+ // it; otherwise synthesize a consistent error from the status.+ const data: unknown = response.data;+ if (isErrorEnvelope(data)) {+ const { code, message, url, errors } = data.error;+ throw new APIError({+ httpStatusCode: response.status || 500,+ error: {+ code: code ?? '',+ message: message ?? '',+ url: url ?? '',+ errors: (errors ?? []).map((e) => ({ message: e.message ?? '' })),+ },+ });+ }throw new APIError({httpStatusCode: response.status || 500,error: {- code: response.data.error.code,- message: response.data.error.message,- url: response.data.error.url ?? '',- errors: (response.data.error.errors ?? []).map((e) => ({- message: e.message ?? '',- })),+ code: 'UPSTREAM_UNAVAILABLE',+ message: error.message || 'Something went wrong',+ url: '',+ errors: [],},});}@@ -62,9 +99,7 @@ export function convertToApiError(return new APIError({httpStatusCode: response?.status || error.status || 500,error: {- code:- errorData?.code ||- String(response?.status || error.code || 'unknown_error'),+ code: errorData?.code || 'UPSTREAM_UNAVAILABLE',message:errorData?.message ||response?.statusText ||diff --git a/frontend/src/api/ErrorResponseHandlerV2.ts b/frontend/src/api/ErrorResponseHandlerV2.tsindex 2ef6a5d44b..b6d6200775 100644--- a/frontend/src/api/ErrorResponseHandlerV2.ts+++ b/frontend/src/api/ErrorResponseHandlerV2.ts@@ -2,19 +2,38 @@ import { AxiosError } from 'axios';import { ErrorV2Resp } from 'types/api';import APIError from 'types/api/error';+function isErrorV2Resp(data: unknown): data is ErrorV2Resp {+ return (+ typeof data === 'object' &&+ data !== null &&+ 'error' in data &&+ typeof (data as ErrorV2Resp).error?.code === 'string'+ );+}+// reference - https://axios-http.com/docs/handling_errorsexport function ErrorResponseHandlerV2(error: AxiosError<ErrorV2Resp>): never {const { response, request } = error;// The request was made and the server responded with a status code// that falls out of the range of 2xxif (response) {+ // response.data isn't guaranteed to be a V2 envelope (e.g. a gateway 5xx+ // with an HTML/empty body during a deploy), so verify the shape first.+ const data: unknown = response.data;+ if (isErrorV2Resp(data)) {+ const { code, message, url, errors } = data.error;+ throw new APIError({+ httpStatusCode: response.status || 500,+ error: { code, message, url, errors },+ });+ }throw new APIError({httpStatusCode: response.status || 500,error: {- code: response.data.error.code,- message: response.data.error.message,- url: response.data.error.url,- errors: response.data.error.errors,+ code: 'UPSTREAM_UNAVAILABLE',+ message: error.message || 'Something went wrong',+ url: '',+ errors: [],},});}diff --git a/frontend/src/api/__tests__/ErrorResponseHandlerV2.test.ts b/frontend/src/api/__tests__/ErrorResponseHandlerV2.test.tsnew file mode 100644index 0000000000..0c94ba21a8--- /dev/null+++ b/frontend/src/api/__tests__/ErrorResponseHandlerV2.test.ts@@ -0,0 +1,126 @@+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp } from 'types/api';+import APIError from 'types/api/error';++function asAxiosError(partial: Partial<AxiosError>): AxiosError<ErrorV2Resp> {+ return partial as AxiosError<ErrorV2Resp>;+}++// ErrorResponseHandlerV2 always throws — capture the APIError so assertions stay+// unconditional.+function runHandler(error: AxiosError<ErrorV2Resp>): APIError {+ try {+ ErrorResponseHandlerV2(error);+ } catch (thrown) {+ return thrown as APIError;+ }+ throw new Error('expected ErrorResponseHandlerV2 to throw');+}++type ExpectedError = {+ httpStatusCode: number;+ code: string;+ message: string;+ errors: { message: string }[];+};++// One row per response shape the handler must normalize. New shapes (with+// different bodies) can be added here without a new test block.+const cases: {+ name: string;+ error: AxiosError<ErrorV2Resp>;+ expected: ExpectedError;+}[] = [+ {+ name: 'well-formed V2 error envelope',+ error: asAxiosError({+ message: 'Request failed with status code 400',+ response: {+ status: 400,+ data: {+ error: {+ code: 'bad_request',+ message: 'Invalid dashboard payload',+ url: 'https://signoz.io/docs',+ errors: [{ message: 'name is required' }, { message: 'name too long' }],+ },+ },+ } as AxiosError['response'],+ }),+ expected: {+ httpStatusCode: 400,+ code: 'bad_request',+ message: 'Invalid dashboard payload',+ errors: [{ message: 'name is required' }, { message: 'name too long' }],+ },+ },+ {+ // Regression: during a deployment the gateway returns a 5xx with a+ // non-envelope body. Reading response.data.error.code used to throw a+ // TypeError from inside the handler itself. See engineering-pod#5760.+ name: '5xx with a non-envelope HTML body',+ error: asAxiosError({+ message: 'Request failed with status code 503',+ response: {+ status: 503,+ data: '<html><body>503 Service Temporarily Unavailable</body></html>',+ } as AxiosError['response'],+ }),+ expected: {+ httpStatusCode: 503,+ code: 'UPSTREAM_UNAVAILABLE',+ message: 'Request failed with status code 503',+ errors: [],+ },+ },+ {+ name: '5xx with an empty body',+ error: asAxiosError({+ message: 'Request failed with status code 502',+ response: {+ status: 502,+ data: undefined,+ } as AxiosError['response'],+ }),+ expected: {+ httpStatusCode: 502,+ code: 'UPSTREAM_UNAVAILABLE',+ message: 'Request failed with status code 502',+ errors: [],+ },+ },+ {+ name: 'no response received (network error)',+ error: asAxiosError({+ message: 'Network Error',+ code: 'ERR_NETWORK',+ name: 'AxiosError',+ request: {},+ }),+ expected: {+ httpStatusCode: 500,+ code: 'ERR_NETWORK',+ message: 'Network Error',+ errors: [],+ },+ },+];++describe('ErrorResponseHandlerV2', () => {+ it.each(cases)(+ 'normalizes $name into a consistent APIError',+ ({ error, expected }) => {+ const apiError = runHandler(error);++ expect(apiError).toBeInstanceOf(APIError);+ expect(apiError.getHttpStatusCode()).toBe(expected.httpStatusCode);+ expect(apiError.getErrorCode()).toBe(expected.code);+ expect(apiError.getErrorMessage()).toBe(expected.message);+ // The sub-error messages feed several parts of the UI, so assert them.+ expect(apiError.getErrorDetails().error.errors).toStrictEqual(+ expected.errors,+ );+ },+ );+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.tsindex 1de17b1219..79ab1b983d 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelStatus/__tests__/utils.test.ts@@ -51,7 +51,7 @@ describe('panelStatusFromError', () => {it('falls back to the error message when there is no structured body', () => {expect(panelStatusFromError(new Error('boom'))).toStrictEqual({- code: 'unknown_error',+ code: 'UPSTREAM_UNAVAILABLE',message: 'boom',docsUrl: undefined,messages: [],diff --git a/frontend/src/utils/errorUtils.ts b/frontend/src/utils/errorUtils.tsindex b0b67a66ad..c818b3ac33 100644--- a/frontend/src/utils/errorUtils.ts+++ b/frontend/src/utils/errorUtils.ts@@ -42,7 +42,12 @@ export function toAPIError(try {ErrorResponseHandlerForGeneratedAPIs(error);} catch (apiError) {- if (apiError instanceof APIError) {+ // UPSTREAM_UNAVAILABLE means the handler couldn't find a backend error code+ // (non-envelope body); prefer the caller's context-specific defaultMessage.+ if (+ apiError instanceof APIError &&+ apiError.getErrorCode() !== 'UPSTREAM_UNAVAILABLE'+ ) {return apiError;}}