Laravel - Test script errors to return certain status to AJAX

2

In an application in Laravel I have several scripts using ajax. All expect a response from the controller script and, if true, I run a certain function with ajax ' success '

Example of how I'm doing:

script.js

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

TestController.php

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

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

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

But I need it to return false in case of an error. But I have no idea and how to test this, I wanted to add an error test for all the scripts (and I do not even know if it is correct or necessary) in several cases ( database query ), working with < strong> session and etc). I know the try / catch but I've never used it and I can hardly see anyone using some code, so I'm kind of lost with it.

    
asked by anonymous 11.05.2016 / 17:04

1 answer

2

First option: The Laravel pattern

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

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

  return ['error' => false];

So you can handle 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: Customizing exception rendering:

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

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

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

/**
     * 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, you have good suggestions on how to work with Laravel errors through Ajax:

11.05.2016 / 17:19