Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ajax catch 500 Internal server error

I am using Laravel with ajax, and in my controller I have a try - catch block:

try {
        something...
    } catch (\Exception $e) {
        return response()->json([
            'status' => 'error',
            'message'=> 'error message'
        ]);
    }

I am using this to show the error message in a div on the page.

This is working, but not if the error is a 500 - internal server error (example: tokenmismatchexception).

Then the error is not caught by the catch-block, and essentially the user is not notified of any error (other than in the console).

Is there a way I can catch such errors, and display an error in the same div as I usually do?

like image 420
Bergkamp10 Avatar asked Mar 02 '17 12:03

Bergkamp10


1 Answers

That is because you might not have included the error section. Make your jQuery Ajax code like:

    $.ajax({
        url     : '/yoururl',
        method    : 'POST',
        data    :
        {
            name:"test"
        },
        success   : function(response)
        {
           //USE THIS SECTION WHEN ITS SUCCESS
        },
        error : function(e)
        {
          //SHOW ERROR TO USER HERE THIS SECTION IS CALLED IN CASE OF ERRORS TO SEE THE OBJECT OF the error use console.log(e);
        }
    });
like image 180
Shakti Phartiyal Avatar answered Sep 29 '22 06:09

Shakti Phartiyal