Error Handling Problems - PHP Laravel

Asked

Viewed 1,504 times

0

I’m doing an API and I have a little problem when I do error treatments.. To better understand I’ll put the code below and then explain what happens.

My route to calling my API:

Route::get('lists', function () {
                    header("Access-Control-Allow-Origin: *");

                    $user = new UserClass();

                    return $user->getList();
                });

My Class:

    public function getList()
    {
        try {
            $result = $this->handleData();

            return response()->json([
                'message' => '',
                'data' => $result,
                'result' => true,
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
                'data' => '',
                'result' => false,
            ], 401);
        }
    }

    public function handleData()
    {
        $payload = request()->all();

        if (($payload['token'] ?? false)) {
            throw new \Exception("Necessário informar um token");
        }

        if (($payload['company_id'] ?? false)) {
            throw new \Exception("Necessário preencher todos os dados");
        }

        $data = [];
        $users = UserCompany::where('company_id', $payload['company_id'])->get();

        foreach ($users as $user) {
            $data[] = [
                'name' => $user->first_name,
                'id' => $user->id,
            ];
        }

        return $data;
    }

The Return works in parts, the example message that a token has not been informed it shows, but is returning me as a system error and not in JSON format, see below as that is returning:

<h1>
                                                    <i class="icon-power-off warning"></i> Error
                                                </h1>
                                                <p class=lead>We're sorry, but an unhandled error occurred. Please see the details below.</p>
                                                <div class=exception-name-block>
                                                    <div>Necessário informar um token</div>
                                                    <p>[...]/classes/User.php 
                                                        <span>line</span> 40
                                                    </p>
                                                </div>

What I did or didn’t do?

1 answer

1


I believe it’s not returning the way you want it to because this code is importing the Exception wrongly:

} catch (Exception $e) {

It should be like this:

} catch (\Exception $e) {

Before, the Exception was imported from App\UserClass\Exception, and the second form, imports from the root \Exception.


Next, an alternative answer.

I’ve already answered a similar question, in case you’re curious look at this link.

The Laravel it has its class that treats exceptions but it does not differentiate whether what you are building is an API or a normal website.

Then you need to implement a treatment so that exceptions it throws return in Json format. For that, you need to go in the file App\Exceptions\Handler.php and edit the function render and implement the following logic.

if($request->expectsJson())
{
    // Aqui você implementa um tratamento as exceções que necessitam de um retorno em JSON.
}

Just like in the original post, I would suggest you do it that way:

use Symfony\Component\HttpFoundation\Response;
... 

if($exception instanceof NotFoundHttpException)
    return response()->json([
        'messages' => 'Recurso não encontrado'
    ], Response::HTTP_NOT_FOUND);

But looking for your code instead of using the following code to throw exceptions:

throw new \Exception("Necessário informar um token");

You used, and there would be no need for a try-catch:

use Symfony\Component\HttpFoundation\Response;
... 

return response()->json([
    'message' => 'Necessário informar um token'
], Response::BAD_REQUEST);

And that way, it eliminates having to touch Handler.php no need other than to return in a more pleasant format with a custom exception code, but of course, standard exceptions you would need to implement a Handler.php.

  • I understood, but the way you suggested last I would already be returning inside the getList() method, and the way I would be able to catch the error inside Catch().. Or I could?

  • I hadn’t realized the try-catch... But no, you wouldn’t treat him at catch but it would return the error message anyway. Reviewing your code again, I believe it is not capturing the exception to be Exception and not \Exception. Anyway, I would recommend not using try-catch in cases like yours, and yes, create a custom exception or return the error as in the examples I gave.

  • @Crazy, forgive my mistake in understanding your problem, I edited the answer and I believe you now solve your problem. I kept the original answer also just to show a good practice that I use in my projects.

  • was just that, missed the Catch Bar inside... Solved!!! Thanks brother!

Browser other questions tagged

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