0

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 ?

0

3 Answers 3

1

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);
    });
},

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

Comments

0

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) => {
     /*...*/
  })

Comments

0

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);

   }
};

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.