H
Hono2d ago
Phantom

Update the default validator to return custom error response

hey guys, I want to update the default zValidator of hono to return custom error objects. Right now, it returns something like this:
{
"success": false,
"error": {
"issues": [
{
"validation": "email",
"code": "invalid_string",
"message": "Invalid email",
"path": [
"email"
]
}
],
"name": "ZodError"
}
}
{
"success": false,
"error": {
"issues": [
{
"validation": "email",
"code": "invalid_string",
"message": "Invalid email",
"path": [
"email"
]
}
],
"name": "ZodError"
}
}
but I want it to return {message:"message"}
19 Replies
Arjix
Arjix2d ago
Easiest way is to just make a global middleware, that looks at the status code, if it is 400, and matches the above structure, replace it with another json
const errorMiddleware = createMiddleware(async (ctx, next) => {
const ret = await next();

if (ctx.res.status === 400) {
const mimeType = ctx.res.headers.get("Content-Type");
if (mimeType?.starts with("application/json") {
const json = ctx.res.json();
// do stuff
return new Response(ctx.res, {
body; JSON.stringify({})
});
}
}
return ret;
});
const errorMiddleware = createMiddleware(async (ctx, next) => {
const ret = await next();

if (ctx.res.status === 400) {
const mimeType = ctx.res.headers.get("Content-Type");
if (mimeType?.starts with("application/json") {
const json = ctx.res.json();
// do stuff
return new Response(ctx.res, {
body; JSON.stringify({})
});
}
}
return ret;
});
Think of that as pseudocode, because I wrote it on my phone
ambergristle
ambergristle2d ago
Have you tried setting the hook? I like rolling my own to reduce repetition, but there are a few different paths you could take Here’s an article I wrote breaking down common options: https://dev.to/fiberplane/hacking-hono-the-ins-and-outs-of-validation-middleware-2jea Throwing to a custom error handler (or hono’s onError) works as well, but I prefer to keep my error processing logic together with my validation
Phantom
PhantomOP2d ago
setting defaultHook worked
ambergristle
ambergristle2d ago
It makes it easier to swap out validators, if you need to, and it means that downstream error handlers only need to care about generating the response
Phantom
PhantomOP2d ago
No description
Arjix
Arjix2d ago
Only returning the first error?
Phantom
PhantomOP2d ago
yes this is what the client demanded
Arjix
Arjix2d ago
I hate clients
Phantom
PhantomOP2d ago
me too but I love money
Arjix
Arjix2d ago
Are you freelancing or smth?
Phantom
PhantomOP2d ago
work had some backlog so working on sunday to cover it before demo on wednesday
Arjix
Arjix2d ago
Good luck!
Phantom
PhantomOP2d ago
thanks
Arjix
Arjix2d ago
This may not have been useful for your particular issue since there was a better way, but it is useful if you want to apply transformations to the json response. E.g. I use it to rename all _id to id when returning data from mongodb Should I have used DTOs instead? Yes Am I working on a legacy backend? Also yes, so the least effort solution is the best, unless I want to rewrite a lot of code
ambergristle
ambergristle2d ago
Why would you recommend a pattern that you then acknowledge to be bad practice? Or promote low-effort development? There’s a difference between over-engineering and cutting corners
Arjix
Arjix2d ago
Eh, it's fine really I don't consider it bad, I just know there are better ways of doing it If performance and memory is important to you, then it's probably a "bad" solution, bc you are serializing/deserializing and serializing once again the response Other than that, I see no downside Sometimes you are left with no choice, and it's good to know all the possible ways of solving smth I'd like to clarify that I am in the process of adding DTOs everywhere to fix this use-case Only to be in more control of the data returned
ambergristle
ambergristle2d ago
I feel it. Sometimes you don’t have a choice. And if someone specifies that they don’t have alternatives, then it would be a solid suggestion But there are devs on this server with all levels of experience, including folks who are just starting out. And they may not have the skill to make that distinction Separating your data formatting from your db calls/object constructors is fragile, at best, and as a general rule, it’s not something I think we should be suggesting unless OP has said they don’t have any other options
Arjix
Arjix2d ago
True, from now on I'll resist posting sub-optimal solutions w/o knowing the experience of the other person
ambergristle
ambergristle2d ago
fwiw, i really appreciate your enthusiasm + desire to help others i think it's awesome that you shared your solution RE react-pdf. your willingness to share your knowledge + expertise without being asked is dope i wish more ppl were like that

Did you find this page helpful?