Laravel - Test script errors to return certain status to AJAX

Asked

Viewed 899 times

2

In an application in Laravel I have several scripts using ajax. Everyone expects a response from the controller script and, if it returns true, I run a certain function with the 'Success' ajax

Example of how I’m doing:

script js.

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: '/teste',
    data: {value:value},
    success: function(data){
        //Alguma função
    }
});

Testecontroller.php

public function teste(Request $request){
    $value = $request->value;

    /* Alguma função com o value*/

    return response()->json(['success' => true]);
}

But I need that, in case of error, return false. Only I have no idea and how to test this, I wanted to add a test of errors to all scripts(and I don’t even know if it’s correct or necessary ) in several cases (query database, working with session etc). I know the Try/catch but never used and hardly see in some code someone using, so I’m kind of lost with this.

1 answer

2

First option: The Laravel pattern

Honestly, if it were me, I would use the standard way that Laravel treats data. I mean, when an error occurs and the request is Ajax, the Laravel returns ['error' => 'Mensagem da exceção'].

In analyzing this, I standardized that all my ajax that successfully return would have the following return:

  return ['error' => false];

Thus, you can treat all your ajax requests as follows:

 $.ajax({
      url: url,
      success: function(response)
      {
           if (response.error)
            {
               return alert("Ocorreu o erro " + response.error);
            }

            alert('Foi feito com sucess');
      }
});

Second option: Customise exception rendering:

If you are using Laravel 5, inside the folder app/Exceptions there is a class called Handler. He’s the exception handler.

You can change it and add a check that if it is ajax, will return the ['success' => false] that you want.

To do this, you need to change the method render:

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {

        if ($this->isHttpException($e) && $request->ajax())
        {
            return response()->json(['success' => false, 'detail' => (string) $e], 422);
        }

        return parent::render($request, $e);
    }

Here in these articles, there are good suggestions on how to work with Laravel through Ajax:

  • And what do I return from the controller? If I do not return a Success-true then the 'Success' method of ajax does not run.

  • In the link examples, you are teaching to capture errors in Ajax. When you return 422 status, you have to add error: in your $.ajax

Browser other questions tagged

You are not signed in. Login or sign up in order to post.