Skip to content

Instantly share code, notes, and snippets.

@sentiasa
Last active June 6, 2023 02:00
Show Gist options
  • Save sentiasa/604e538b6aff809afc1480687e1adc78 to your computer and use it in GitHub Desktop.
Save sentiasa/604e538b6aff809afc1480687e1adc78 to your computer and use it in GitHub Desktop.
Laravel Ajax Error Hadling
export default {
methods: {
handleAjaxError(err) {
let errorText = err.response.data.message;
if (err.response.status === 422) {
errorText = this.convertLaravelErrorBagToString(err.response.data.errors);
}
// Here errorText variable should be ready to show all the error message in a string format,
// which I could simply display it.
// In this instance, I preferred using SweetAlert;
swal('Something went wrong', errorText, 'error');
},
// Implode Laravel ErrorBag into multi-line string
convertLaravelErrorBagToString(errorsArr) {
let errorBag = [];
Object.values(errorsArr).forEach(error_msg => {
errorBag.push(error_msg);
});
return errorBag.join('\n')
},
}
}
@sentiasa
Copy link
Author

Usage:

axios.post(url, obj)
   .then(response => {
         // handle success
    })
   .catch(error => { 
       this.handleAjaxError(error);
   });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment