🔥 Easily Handle Laravel Errors within Ajax

Kodeas
2 min readJun 30, 2020

--

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 👊

--

--