Custom Error Response in Route Handlers
Answered
LAWLESS posted this in #help-forum
![Avatar](https://cdn.discordapp.com/avatars/552424182768730113/fa97b9ba7871d0aaeebd49bd790791ee.webp?size=256)
LAWLESSOP
How can I handle error and return error when working with route handlers
I have the following code and I want to return custom error status
I have the following code and I want to return custom error status
import backend from '@/utils/axios'
export async function POST(request: Request) {
const body = await request.json()
try {
const res = await backend.post('/auth/sign-up', body)
const data = await res.data
return Response.json(data)
} catch (error: any) {
if (error.response.status === 409) {
return Response.json({
message: 'Email already exists',
})
}
return Response.error()
}
}
4 Replies
![Avatar](https://cdn.discordapp.com/avatars/484037068239142956/44415017de6fed2ccd5d44b4b2051ac0.webp?size=256)
joulev
return Response.json({ error: "Unauthorized" }, { status: 401 })
Answer
![Avatar](https://cdn.discordapp.com/avatars/552424182768730113/fa97b9ba7871d0aaeebd49bd790791ee.webp?size=256)
LAWLESSOP
Thanks 😇
Its worked
Do you have a docs I can refer for this 😅
In the nextjs docs there wasn't much for this
Its worked
Do you have a docs I can refer for this 😅
In the nextjs docs there wasn't much for this
![Avatar](https://cdn.discordapp.com/avatars/552424182768730113/fa97b9ba7871d0aaeebd49bd790791ee.webp?size=256)
LAWLESSOP
Thanks