Problems with error handling - PHP Laravel

0

I'm doing an API and I'm having a little problem when I make error treatments .. To understand better 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 function works in parts, the example message that a token has not been told it shows, however it is returning me as a system error and not in JSON format, see below how it 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 did I do or did not do?

    
asked by anonymous 09.09.2018 / 15:37

1 answer

1

I think it's not returning the way you want because this code is importing Exception wrongly:

} catch (Exception $e) {

It should look like this:

} catch (\Exception $e) {

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

The following is an alternative answer.

I already answered a similar question, if you're curious, look at this .

Laravel it has its class that handles exceptions but it does not differentiate if what you are building is an API or a normal site.

So you need to implement a treatment for which exceptions it throws return in Json format. To do this, you need to go to the App\Exceptions\Handler.php file and edit the render function and implement the following logic.

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

As with the original post, I would suggest you do it this way:

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

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

But looking at 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 thus, it eliminates having to fiddle with Handler.php without needing to return in a more nice format with a custom exception code, but of course, standard exceptions you would need to implement a treatment in Handler.php .

    
09.09.2018 / 18:06