Skip to content

Commit 1562d56

Browse files
authored
improvement(api): log the v2 error code, field, and refusal reason on the request's closing line (#10033)
* improvement(api): log the v2 error code, field, and refusal reason on the request's closing line * improvement(api): tag the returned response instead of the request, and log only the declared top-level field
1 parent 56893cb commit 1562d56

3 files changed

Lines changed: 53 additions & 4 deletions

File tree

‎apps/sim/app/api/v2/lib/response.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
type OrchestrationErrorCode,
2323
} from '@/lib/core/orchestration/types'
2424
import type { HttpError } from '@/lib/core/utils/http-error'
25+
import { describeResponseError } from '@/lib/core/utils/response-error'
2526
import type { RateLimitResult } from '@/app/api/v1/middleware'
2627

2728
/**
@@ -217,7 +218,7 @@ export function v2Error(
217218
const retryAfterSeconds = options.omitRetryAfter
218219
? undefined
219220
: RETRY_AFTER_SECONDS_BY_STATUS[status]
220-
return NextResponse.json(
221+
const response = NextResponse.json(
221222
{ error },
222223
{
223224
status,
@@ -229,6 +230,15 @@ export function v2Error(
229230
},
230231
}
231232
)
233+
const reason = detailCode(options.details)
234+
describeResponseError(response, { errorCode: code, ...(reason ? { errorReason: reason } : {}) })
235+
return response
236+
}
237+
238+
/** The cause a refusal names in `details.code`, a closed vocabulary safe to log. */
239+
function detailCode(details: unknown): string | undefined {
240+
if (typeof details !== 'object' || details === null || !('code' in details)) return undefined
241+
return typeof details.code === 'string' ? details.code : undefined
232242
}
233243

234244
/** Renders a trusted typed HTTP error without changing the v2 envelope. */
@@ -267,9 +277,17 @@ export function v2ValidationError(error: ZodError, slice?: RequestSlice): NextRe
267277
? issueMessage.slice(fieldLabel.length)
268278
: issueMessage
269279
const location = [slice, ...path].filter((part) => part !== undefined && part !== '').join('.')
270-
return v2Error('BAD_REQUEST', location ? `${location}: ${message}` : message, {
280+
const response = v2Error('BAD_REQUEST', location ? `${location}: ${message}` : message, {
271281
details: serializeZodIssues(error),
272282
})
283+
// Deeper segments can be record keys the caller wrote (an import's CSV headers); no slice is itself a record.
284+
const field = [slice, path[0]].filter((part) => part !== undefined && part !== '').join('.')
285+
describeResponseError(response, {
286+
errorCode: 'BAD_REQUEST',
287+
...(field ? { errorField: field } : {}),
288+
...(error.issues[0] ? { errorReason: error.issues[0].code } : {}),
289+
})
290+
return response
273291
}
274292

275293
/**
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* The machine-readable part of an error response, kept beside the response so
3+
* the route handler's closing log line can be grouped by why a request was
4+
* refused without reading the body. Never the message, which can quote user
5+
* input.
6+
*/
7+
export interface ResponseErrorSummary {
8+
/** The stable error code the body carries, e.g. `BAD_REQUEST`. */
9+
errorCode: string
10+
/** For a validation failure, the request slice and its declared top-level field, e.g. `body.mapping`. */
11+
errorField?: string
12+
/** The cause the refusal named (`READ_ONLY_API_KEY`) or the validation issue kind (`invalid_type`). */
13+
errorReason?: string
14+
}
15+
16+
/**
17+
* Keyed by the response object, so only a response a route actually returns is
18+
* ever read back. One built only to extract its message is never logged.
19+
*/
20+
const summaries = new WeakMap<Response, ResponseErrorSummary>()
21+
22+
/** Records what `response` tells its caller; a later call for the same response replaces it. */
23+
export function describeResponseError(response: Response, summary: ResponseErrorSummary): void {
24+
summaries.set(response, summary)
25+
}
26+
27+
/** What `describeResponseError` recorded for `response`, if anything. */
28+
export function readResponseError(response: Response): ResponseErrorSummary | undefined {
29+
return summaries.get(response)
30+
}

‎apps/sim/lib/core/utils/with-route-handler.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { ADMISSION_RETRY_AFTER_SECONDS } from '@/lib/core/admission/transient-fa
1515
import { FILE_DELIVERY_CSP_PATH_PATTERN, getMainCSPPolicy } from '@/lib/core/security/csp'
1616
import { HttpError } from '@/lib/core/utils/http-error'
1717
import { generateRequestId } from '@/lib/core/utils/request'
18+
import { readResponseError } from '@/lib/core/utils/response-error'
1819
import { MAX_CALL_CHAIN_DEPTH, parseCallChain, SIM_VIA_HEADER } from '@/lib/execution/call-chain'
1920
import { trackInFlightRequest } from '@/lib/monitoring/in-flight-requests'
2021
import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server'
@@ -274,9 +275,9 @@ export function withRouteHandler<T>(
274275
const duration = Date.now() - startTime
275276

276277
if (status >= 500) {
277-
logger.error('Server error response', { status, duration })
278+
logger.error('Server error response', { status, duration, ...readResponseError(response) })
278279
} else if (status >= 400) {
279-
logger.warn('Client error response', { status, duration })
280+
logger.warn('Client error response', { status, duration, ...readResponseError(response) })
280281
} else if (status > 0) {
281282
logger.info('OK', { status, duration })
282283
}

0 commit comments

Comments
 (0)