I would like to validate response of request in silent (for example only log to console) because I don't want to interrupt user with this information (also response schema is used in elysiajs swagger plugin so it is useful to have it), but I still want to know when this happens. Also I want to validate body strictly and return 400.
This is far as I got, I can use onError and catch an error, but can't differentiate between body validation and response validation.
import { Elysia, t } from "elysia";
export const PostLoginRoute = new Elysia()
.onError((error) => {
console.log("error", error);
return new Response(error.toString());
})
.post("/login", ({ body }) => body, {
body: t.Object(
{
username: t.String(),
password: t.String(),
},
{
description: "Expected an username and password",
}
),
response: t.Object({
username: t.String(),
password: t.String(),
id: t.String(),
}),
detail: {
summary: "Sign in the user",
tags: ["authentication"],
},
});
error content
error: Invalid response, 'id': Expected string
Expected: {
"username": "",
"password": "",
"id": ""
}
Found: {
"username": "user",
"password": "pass"
}
code: "VALIDATION"
at new K0 (/hi-elysia/node_modules/elysia/dist/bun/index.js:8:25881)
,
set: {
headers: {},
status: 500
},
code: "VALIDATION"
}
I can parse message of error and find Invalid response substring, but I kind of dislike this idea. Is there any better approach?
Take a look at this page: https://elysiajs.com/patterns/error-handling.html
There is an example showing exactly how to do that.
In short, add local error handler, switch on an error code, than map through errors looking into path property.
X - is an object containing info you need.
Something like this: