Next.js Discord

Discord Forum

Custom Error Response in Route Handlers

Answered
LAWLESS posted this in #help-forum
Open in Discord
Avatar
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
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()
  }
}
Answered by joulev & fuma pray for Schneider
return Response.json({ error: "Unauthorized" }, { status: 401 })
View full answer

4 Replies

Avatar
joulev & fuma pray for Schneider
return Response.json({ error: "Unauthorized" }, { status: 401 })
Answer
Avatar
LAWLESSOP
Thanks 😇
Its worked

Do you have a docs I can refer for this 😅
In the nextjs docs there wasn't much for this
Avatar
joulev & fuma pray for Schneider
Avatar
LAWLESSOP
Thanks