š„ Easily Handle Laravel Errors within Ajax
There are bunch of ways you receive Laravel errors in front-end and inside your ajax request, you need to parse and display the errors nicely.
Inside blade, itās pretty easy to handle and display errors but inside javascript?
In my projects, I realised a pattern that I was repeating myself for handling an error message properly. Finally, I figured out a tidy way!
Iāll use Vue in this example but you should be good to use it with other frameworks or even with vanilla javascript.
The reason:
When I make an ajax call inside a component, I donāt want to think about error-handling every single time. I didnāt even want to think about it.
All I wanted was: āJust display the error!ā
axios.post(url, obj)
.then(response => { // success path })
.catch(error => {
// bunch of the repetitive code
// to parse the error and
// display it nicely
})
However, I wanted to handle it as:
axios.post(url, obj)
.then(response => { // success path })
.catch(error => { this.handleAjaxError(error); })
The Solution
First, I create a global mixin inside my Vue called error-handling.js
and attach it to my Vue instance.
//app.jsimport ErrorHandling from "./mixins/error-handling";
Vue.mixin(ErrorHandling);
Then, my error-handling
mixin looks like:
Explanation
#1. In the first part of handleAjaxError()
, it handles my custom errors.
if (!$canDoIt) {
return response()->json(['message' => "You can't do it"], 401);
}
That can be accessed as:
err.response.data.message;
#2. ā422ā error-code is a validation error so I know the error response is in Laravelās ErrorBag format.. And implode the array into a multi-line readable string.
request()->validate([
'rule_name' => 'required'
])
Usage
axios.post(url, obj)
.then(response => {})
.catch(error => { this.handleAjaxError(error) });
I hope you like this approach, if you do please do a š
Of course this can be improved! If you do improve it please share it with me too š. Or if you already have a better solution definitely let me know :)
Sharing is caring š