Custom Error Response in Route Handlers
Answered
LAWLESS posted this in #help-forum
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
@LAWLESS 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
ts
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()
}
}
return Response.json({ error: "Unauthorized" }, { status: 401 })
Answer
@joulev `return Response.json({ error: "Unauthorized" }, { status: 401 })`
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
LAWLESSOP
Thanks