Nika Kurashvili
Nika Kurashvili

Reputation: 6462

Laravel returned error not shown in front-end

I have something like this in a Laravel API for one of the routes:

return response()->json(['message' =>  "Couldn't Price the car"], 500);

In the front-end, I have

try {
 let data = await Axios.get("blax", {});    
} catch(err) {
  console.log(err.message);
}

err.message just shows default message:

request failed with status code 500

instead of showing:

Couldn't Price the car

How do I show my custom message?

Upvotes: 4

Views: 293

Answers (3)

Omer Abdelmajeed
Omer Abdelmajeed

Reputation: 364

Updated

responseJSON is not defined it's just response

try this the console.log(err.response.message) as following:

try{
 let data = await Axios.get("blax", {});

}catch(err){
  console.log(err.response.message);
}

Upvotes: 1

Sølve
Sølve

Reputation: 4406

It seems to me that it catches perfectly:

new Vue({
  el: "#demo",
  data: {
    response: null,
  },
  async created() {
    try {
      let data = await axios.get("https://httpstat.us/500", {});
    } catch (err) {
      console.log('ss', err.message);
      this.response = err.message;
    }
  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>

<div id="demo">
Error: {{response}}
</div>

If you want to minimize your code, you can do .catch directly on the axios call, like so:

let data = axios.get("https://httpstat.us/500", {}).catch(e => e.message);

This catch also uses arrow function stripped down to the minimal. Here is an example of the same arrow function, just "normal":

let data = axios.get("https://httpstat.us/500", {}).catch((e) => {return e.message});

new Vue({
  el: "#demo",
  data: {
    response: null,
  },
  async created() {
    this.response = await axios.get("https://httpstat.us/500", {}).catch(e => e.message);
  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>

<div id="demo">
Error: {{response}}
</div>

Upvotes: 1

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

try using err.response.message

try{
 let data = await Axios.get("blax", {});

}catch(err){
  console.log(err.response.message);
}

Upvotes: 7

Related Questions