psudo
psudo

Reputation: 1568

Catch error with try catch block and display

Error handling middleware in node js backend:

app.use((error, req, res, next) => {
  console.log(error);
  const status = error.statusCode || 500;
  const message = error.message;
  const data = error.data;
  res.status(status).json({ message: message, data: data });
});

I have the following try catch block from my app:

    userLogin() {
    //axios vue instance
      this.$http
        .post("/auth/signup", this.formData)
        .then((res) => {
          // res.status == 201 ? (this.formData = {}) : "";
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
          console.log(err.data.data);
          console.log(err.data.msg);
        });
    },

The output of the above catch block are as follows: [![enter image description here][2]][2]

While my rest api sends the message in following format (seen on Network > Preview)

{
  message: "Validation failed.",
  …
}
data: [{
  location: "body",
  param: "email",
  value: "[email protected]",
  msg: "E-Mail address already exists!"
}]
message: "Validation failed."

I want to access the data array and print its content. How can I access data ?

Upvotes: 0

Views: 1474

Answers (3)

MohKoma
MohKoma

Reputation: 1472

More readable format

async userLogin() {

   try {

       // Call the server
       const {data} = await this.$http.post("/auth/signup", this.formData);

       // If you want message
       let message = data.message;

       // If you want the data object, ex data: [{location: "body"....}]
       let dataObject = data.data;

   } catch (e) {

      // In case of error
      console.log(err.response);

   }
};

Upvotes: 0

psudo
psudo

Reputation: 1568

We can catch custom error message:

userLogin() {
  this.$http
    .post("/auth/signup", this.formData)
    .then((res) => {
      // res.status == 201 ? (this.formData = {}) : "";
      console.log(res);
    })
    .catch((err) => {
      console.log(err.response.data.data);
    });
},

Upvotes: 1

tony19
tony19

Reputation: 138676

Axios stores the actual response in its data prop (unrelated to your API's data property in the response contents), so you could access your data property like this:

this.$http.post('/auth/signup', this.formData)
  .then((res) => {
    const apiResponse = res.data
    console.log(apiResponse.data) // logs `data` property from API response contents
  })
  .catch((err) => {
     /*...*/
  })

Upvotes: 0

Related Questions