How to deal with errors in Next API routes, App Directory
Answered
Common paper wasp posted this in #help-forum
Common paper waspOP
Let say this is my code:
How can I handle errors here?
import { SignUpSchema } from "@/lib/validation";
export async function POST(req: Request) {
try {
const { email, password, fullName } = await req.json();
//Validation
await SignUpSchema.parseAsync(req.body);
return Response.json({ email, password });
} catch (err) {
//How to return user friendly errors?
}
}
How can I handle errors here?
Answered by Cape horse mackerel
I believe you're using zod for the validation. I'd write smth like:
export async function POST(req: Request) {
try {
const { email, password, fullName } = await req.json();
//Validation
const validation = SignUpSchema.safeParse(req.json());
if(!validation.success) {
return Response.json({
message: validation.error.errors
}, { status: 400})
}
return Response.json({ email, password });
} catch (err) {
return NextResponse.json('Server error', { status: 500 });
}
}1 Reply
Cape horse mackerel
I believe you're using zod for the validation. I'd write smth like:
export async function POST(req: Request) {
try {
const { email, password, fullName } = await req.json();
//Validation
const validation = SignUpSchema.safeParse(req.json());
if(!validation.success) {
return Response.json({
message: validation.error.errors
}, { status: 400})
}
return Response.json({ email, password });
} catch (err) {
return NextResponse.json('Server error', { status: 500 });
}
}Answer