0

I am using Vue.js and I need to capture an error of my backend api.

When I try capture the error message, I get an error:

[Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'message' of undefined"

What am I doing wrong?

I have a nodejs router test as:

router.post("/register", async (req, res) => {
  const email = 'teste';
  if (email) {
    //Throw error to test
    return res.status(400).send({
      data: {
        message: "Já existe uma conta com esse email no nosso sistema",
      },
    });
  }
 })

In my vuejs view, I have:

 try {
    //AuthenticationService.register is an axios post 
    const response = await AuthenticationService.register({
            nome: this.nome,
            email: this.email,
            password: this.password,
    });
 } catch (err) {
          console.log("erro", err);
          this.error = err.data.message;
 }
0

1 Answer 1

1

The returned body will not be directly in the caught error message, i.e. it is likely a traditional error which is either an object, string or Exception.

You would need to consume the body of the response (the status code being 400 will throw an error, but the body of the response will still need to be consumed and parsed as JSON).

In axios specifically, this response is included with the error as a property, i.e. err.response. Assuming you are not modifying existing axios behaviour, it will also parse the JSON for you automatically, so you can simply do like so:

try {
   //AuthenticationService.register is an axios post 
   const response = await AuthenticationService.register({
           nome: this.nome,
           email: this.email,
           password: this.password,
   });
} catch (err) {
         console.log("erro", err);
         this.error = err.response.data.message;
}

If you're using the latest versions of Node, you can use the new null propagation operator for extra safety in Vue:

try {
   //AuthenticationService.register is an axios post 
   const response = await AuthenticationService.register({
           nome: this.nome,
           email: this.email,
           password: this.password,
   });
} catch (err) {
         console.log("erro", err);
         this.error = err?.response?.data?.message;
}

This will mean that if any property is null it'll propagate the null instead of throwing an error and potentially halting your program flow. This is also referred to commonly as Optional Chaining and I highly recommend it within Vue as it will prevent a single unexpected null value from breaking your entire view model.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.