Skip to content

Commit 5c61126

Browse files
authored
Improve the validation error message (#428)
Current it doesn't show what fields has errors
1 parent 17abf92 commit 5c61126

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

src/common/utils/httpHandlers.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,18 @@ export const validateRequest = (schema: ZodSchema) => async (req: Request, res:
99
await schema.parseAsync({ body: req.body, query: req.query, params: req.params });
1010
next();
1111
} catch (err) {
12-
const errorMessage = `Invalid input: ${(err as ZodError).errors.map((e) => e.message).join(", ")}`;
13-
const statusCode = StatusCodes.BAD_REQUEST;
14-
const serviceResponse = ServiceResponse.failure(errorMessage, null, statusCode);
15-
res.status(serviceResponse.statusCode).send(serviceResponse);
12+
const errors = (err as ZodError).errors.map((e) => {
13+
const fieldPath = e.path.length > 0 ? e.path.join('.') : 'root';
14+
return `${fieldPath}: ${e.message}`;
15+
});
16+
17+
const errorMessage =
18+
errors.length === 1
19+
? `Invalid input: ${errors[0]}`
20+
: `Invalid input (${errors.length} errors): ${errors.join('; ')}`;
21+
22+
const statusCode = HTTP_STATUS_CODES.BAD_REQUEST;
23+
const serviceResponse = ServiceResponse.failure(errorMessage, null, statusCode);
24+
res.status(serviceResponse.statusCode).send(serviceResponse);
1625
}
1726
};

0 commit comments

Comments
 (0)