Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
Nika Kurashvili Avatar asked Jan 01 '23 19:01

Nika Kurashvili


2 Answers

try using err.response.message

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

}catch(err){
  console.log(err.response.message);
}
like image 162
Saurabh Mistry Avatar answered Jan 03 '23 10:01

Saurabh Mistry


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>
like image 41
Sølve Tornøe Avatar answered Jan 03 '23 09:01

Sølve Tornøe