middleware icon indicating copy to clipboard operation
middleware copied to clipboard

improve docs to recommend patterns for error handling

Open swyxio opened this issue 2 years ago • 2 comments

thanks for this package!

right now if you send in a malformed request, the response isnt very user friendly

image

i'd like to be able to customize that. i see in the code:

https://github.com/honojs/middleware/blob/42f9a1bd77db0dd83078e5499d34634fbb88accb/packages/zod-validator/src/index.ts#L46C5-L48C6

that there's no way to customize using the default pattern, i have to use a "hook". okay, but how do i use hooks? the readme only gives one example and i'm still not very confident about it. more guidance?

swyxio avatar Jan 02 '24 22:01 swyxio

Hi @swyxio !

Here's a snippet. Do you think reading this will help you?

https://hono.dev/snippets/validator-error-handling

If it is not enough, we need to add more information. Also, the location of the documentation is confusing and hard to find, so we would like to improve it.

cc: @sor4chi

yusukebe avatar Jan 02 '24 22:01 yusukebe

I get sama behavior and create a new middleware to handle ZOD errors and get better output :

Middleware:

import { zValidator } from "@hono/zod-validator";
import type { ValidationTargets } from "hono/types";
import { z } from "zod";
import { fromZodError } from "zod-validation-error";

type PayloadKey = keyof ValidationTargets;

export const zodValidatorMiddleware = (payloadKey: PayloadKey, schema: z.ZodTypeAny) =>
	zValidator(payloadKey, schema, (result, c) => {
		if (!result.success) {
			const validationError = fromZodError(result.error);
			return c.json(
				{
					message: validationError.message,
					errors: validationError.details,
				},
				400,
			);
		}
	});


USAGE:

import { supabase } from "@/libs/supabase/client";
import { zodValidatorMiddleware } from "@/middlewares/zodValidator";
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { endTime, startTime } from "hono/timing";
import { z } from "zod";

const authRoutes = new Hono()
	.post(
		"/sign-up",
		zodValidatorMiddleware(
			"json",
			z.object({
				email: z.string(),
				password: z.string().min(8),
			}),
		),
		async (c) => {
			const { email, password } = c.req.valid("json");

			const { data, error } = await supabase.auth.signUp({
				email,
				password,
			});

			if (error) {
				console.log(error);
				throw new Error(error.message, {
					cause: error,
				});
			}

			return c.json(data.user);
		},
	)
export default authRoutes;

Wrong Request ( without email and data format of Password as number ): http://localhost:3000/api/auth/sign-up { "password": 15 }

Response:

{
  "message": "Validation error: Required at \"email\"; Expected string, received number at \"password\"",
  "errors": [
    {
      "code": "invalid_type",
      "expected": "string",
      "received": "undefined",
      "path": [
        "email"
      ],
      "message": "Required"
    },
    {
      "code": "invalid_type",
      "expected": "string",
      "received": "number",
      "path": [
        "password"
      ],
      "message": "Expected string, received number"
    }
  ]
}

Some insight let me know :) @yusukebe @swyxio

CarlosZiegler avatar Jan 07 '24 19:01 CarlosZiegler