Dimitri Borgers
Dimitri Borgers

Reputation: 278

Why can't I access a res.status(400) response outside the catch block?

two questions regarding a NextJS/Typescript website I'm making! Currently, I have an authentication function from the front-end, that is then handled on my backend server. As you can see in the code below, this function returns a res.status(400) when there is an error and a res.status(200) when everything works correctly. However, I can't seem to store this status in the responseVariable that awaits for the function to end. Instead, it immediately displays an error on my front-end console. This, however, isn't true when the status is 200; in which case I can actually print out the returned status. So my two questions are:

  1. Why can't I access the responseVariable when it is a status 400 response?
  2. I understand I can catch the error instead of looking at the responseVariable, but I can't seem to access the "Missing username" message that should be within the error. Logging error.message returns "Request failed with status code 400"; any way to access the custom message within the JSON? Edit: When I try logging error.response.message, I get the error: "Property 'response' does not exist on type 'Error'."

Authentication function called on front-end:

  const handleAuthentication = async () => {
    try {
      const responseVariable = await axios({
        method: 'POST',
        url: '/api/auth',
        data: {
          username: account,
        },
      })
      console.log(responseVariable) //I get here for 200 status, but not 400
    } catch (error) {
      console.log(error.message)
    }
  }

Back-end auth handler:

import type { NextApiRequest, NextApiResponse } from 'next'
import { sign } from 'jsonwebtoken'

const Auth = async (req: NextApiRequest, res: NextApiResponse) => {
   const { username } = req.body

   if (!username) {
     res.status(400).json({ message: 'Missing username' })
     return
   }

   const token = sign({ username },process.env.TOKEN_SECRET as string)

   return res.status(200).json({ token })
  }
}

export default Auth

Upvotes: 1

Views: 573

Answers (2)

jheth
jheth

Reputation: 380

I ran into this exact same issue. Are you using the sentry/nextjs package?

https://github.com/getsentry/sentry-javascript/issues/6670

It was resolved in version 7.30.0

I updated to the latest sentry/nextjs version (7.46.0) and it fixed the issue.

Upvotes: 0

Erfan HosseinPoor
Erfan HosseinPoor

Reputation: 1077

You must use this form for get access to the message that return from api

error.response.data.message

Upvotes: 0

Related Questions