FormRequest validation error returns 500 instead of 422 with errors (after update 5.2)

After upgrading from L5.1 to L5.2, I no longer receive a JSON object as a response to a failed FormRequest request (i.e., an AJAX post request).

I usually get 422 answers like:

[
    email: 'E-mail is invalid',
    firstname: 'Firstname must be at least 2 characters'
]

But now I get a page with 500 error:

500 response page

I guaranteed that my AJAX calls have application/jsona header Accept.

Refresh

, . FormRequest , Laravel. : validate AJAX- Laravel . Laravel JSON, . JSON 422 HTTP.

php artisan make:request StoreBlogPostRequest : php artisan make:request StoreBlogPostRequest (https://laravel.com/docs/5.1/validation#form-request-validation)

+6
3

, , , , app/Exceptions/Handler.php , , , .

App\Exceptions\Handler. : .

app/Exceptions/Handler.php https://laravel.com/docs/5.2/errors#the-exception-handler, , , .

+3

@Mattias!

, 2 , , . .env 500, FormValidator ValidationException ( ). : \\Handler.php

private function handleExceptions($e)
    {
       // Add anywhere in this method the following code
       // It does what the FormValidator does.

        if($e instanceof ValidationException) {

            return redirect()->back()->withErrors($e->validator->getMessageBag()->toArray());
        }

        return response()->view('errors.500', [], 500);
    }
+3

, Laravel 5.7.

/storage/logs/laravel-yyyy-mm-dd.log, . , StoreLocation :

:

[2018-12-13 09:48:09] local.ERROR: Class App\Requests\StoreLocation does not exist

Obviously, I started writing code without having coffee in the first place!

Decision:

use App\Http\Requests\StoreLocation;

I added the correct path to the StoreLocation.php class. After the correction, everything returned to normal and began to send an answer 422.

PS1: to get the logs, make sure that debugging mode is turned on: add APP_DEBUG = true to the .env file

PS2: the log file stores the latest entries at the bottom

0
source

Source: https://habr.com/ru/post/1623114/


All Articles