Skip to content

Error in parsing request body validation errors with Zod #1528

@realityzero

Description

@realityzero

What version of Elysia is running?

1.4.13

What platform is your computer?

Darwin 23.5.0 arm64 arm

What environment are you using

bun 1.3.1

Are you using dynamic mode?

No

What steps can reproduce the bug?

Following the Error Handling doc. We get an exception when using error.detail(error.message).

Image Image

Code snippet:

import Elysia from 'elysia';
import jwt from '@elysiajs/jwt';
import { config } from '../utils/config';
import OtpService from '../services/otp';
import z from 'zod';
import { OtpError } from '../exceptions';

const sendOtpEmailSchema = z.object({
    channel: z.literal("email"),
    otpTo: z.email({ error: "Must be a valid email address" }),
  });
  
  const sendOtpSmsSchema = z.object({
    channel: z.literal("sms"),
    otpTo: z.e164({ error: "Must be a valid phone number with country code" }),
  });
  
const sendOtpSchema = z.discriminatedUnion("channel", [sendOtpEmailSchema, sendOtpSmsSchema]);

export const otpRoutes = new Elysia({ name: 'otpRoutes', prefix: '/otp' })
    .use(
        jwt(
            {
                name: 'jwt',
                secret: config.jwt.secret,
                exp: config.jwt.expiresIn,
            }
        )
    )
    .error({ OtpError })
    .onError(({ code, error, status }) => {
		switch (code) {
			case 'OtpError':
                console.log('error', error);
                return status((error.info.status) as number, { ...error.info })
            case 'VALIDATION':
                return error.detail(error.message)
                // console.log('error', {error: JSON.parse(error.message)});
                // console.log('error', {error, code, status});
                // return status(422, { type: 'VALIDATION', message: 'Validation error', userMessage: error.message } as OtpErrorInfo)
			default:
                // console.log('error', {error: error.message});
                console.log('error', {error, code, status});
				return { error: 'Internal Server Error' }
		}
	})
    .post('/send', async ({ body, set }) => {
        const { channel, otpTo } = body;
        console.log('body', body);
        const data = await OtpService.sendOtp(channel, otpTo);
        return { message: 'OTP sent successfully' };
    }, {
        body: sendOtpSchema,
    })

If we debug using console.log('error', {error: JSON.parse(error.message)});, we find the error needs to be parsed properly when using zod and error.detail(error.message).

Image

What is the expected behavior?

Proper validation error message and status code as per the Error Handling doc.

What do you see instead?

No response

Additional information

No response

Have you try removing the node_modules and bun.lockb and try again yet?

No

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions