Skip to content

Commit 4a7f5fa

Browse files
committed
fix(api): improve error messaging for response validation in Router
- Enhanced error messages to include specific paths for validation errors. - Updated response handling to ensure clearer feedback on invalid responses.
1 parent 27b48ce commit 4a7f5fa

File tree

2 files changed

+15
-15
lines changed

2 files changed

+15
-15
lines changed

packages/http-router/src/Router.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ describe('Router', () => {
625625
expect(response.statusCode).toBe(400);
626626
expect(response.body).toHaveProperty(
627627
'error',
628-
'Invalid response for endpoint GET - http://localhost/api/test. Error: must NOT have additional properties (additionalProperty: asda)',
628+
"Invalid response for endpoint GET - http://localhost/api/test. Error: at path '(root)': must NOT have additional properties (additionalProperty: asda)",
629629
);
630630
});
631631

packages/http-router/src/Router.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -267,30 +267,30 @@ export class Router<
267267
throw new Error(`Missing response validator for endpoint ${req.method} - ${req.url} with status code ${statusCode}`);
268268
}
269269
if (responseValidatorFn && !responseValidatorFn(coerceDatesToStrings(body))) {
270+
const errorMessage = responseValidatorFn.errors
271+
?.map((error: any) => {
272+
const pathDesc = error.instancePath ? `at path '${error.instancePath}'` : "at path '(root)'";
273+
const paramsStr = Object.keys(error.params || {}).length
274+
? ` (${Object.entries(error.params)
275+
.map(([key, value]) => `${key}: ${value}`)
276+
.join(', ')})`
277+
: '';
278+
return `${pathDesc}: ${error.message}${paramsStr}`;
279+
})
280+
.join('\n');
270281
logger.warn({
271282
msg: 'Response validation failed - response does not match route spec',
272283
method: req.method,
273284
path: req.url,
274-
error: responseValidatorFn.errors?.map((error: any) => error.message).join('\n '),
285+
error: errorMessage,
275286
originalResponse: body,
276287
});
277288
return c.json(
278289
{
279290
success: false,
291+
body,
280292
errorType: 'error-invalid-body',
281-
error: `Invalid response for endpoint ${req.method} - ${req.url}. Error: ${responseValidatorFn.errors
282-
?.map(
283-
(error: any) =>
284-
`${error.message} (${[
285-
error.instancePath,
286-
Object.entries(error.params)
287-
.map(([key, value]) => `${key}: ${value}`)
288-
.join(', '),
289-
]
290-
.filter(Boolean)
291-
.join(' - ')})`,
292-
)
293-
.join('\n')}`,
293+
error: `Invalid response for endpoint ${req.method} - ${req.url}. Error: ${errorMessage}`,
294294
},
295295
400,
296296
);

0 commit comments

Comments
 (0)