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?
try using err.response.message
try{
let data = await Axios.get("blax", {});
}catch(err){
console.log(err.response.message);
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With