Laravel Restful Api - JSON errors instead of HTML

Asked

Viewed 990 times

7

How do I get the controller to automatically return a replay to the client in JSON format instead of HTML in case of an error (e. g. error 404, 500, 419, etc.). For example, if there is error 500 in Laravel, I would like it to return as follows:

{status: 500,
 message: "Trying to get id os non object at UserController.php line 150"
 trace: {...}
}

I realized that this is already done in the Web application routes (web.php) when making an internal request in Ajax. I’m assembling an Android application that requests in my web application, which is being used as a Webservice, and I’m not able to handle the errors, because they are being returned in HTML format (Document). Thanks for your help.

  • already tried to edit the App/Exception/Handler? you can modify it and return a replay with the data you want!

2 answers

2


Eai Luan, you can treat this directly in your controller method, like this:

    try {

        //Código aqui, abaixo a variavel $data retorna o valor que vc quer consumir.

        return response()->json([
            'info' => 'success',
            'result' => $data
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'info' => 'error',
            'result' => 'Não foi possível capturar os dados do usuário!.'
            'error' => $e->getMessage(),
        ], 400);
    }

You will put the Try inside the method, and inside the Try you will pass the data you want to send (Where is the comment). in the "Return" inside the Try the variable $data will return to you the data you want.

Where you see here the number "400" is the access error, if you prefer you can change it to for example: 500 or 404.

If the error occurs it will exit Try and will enter the catch, where it will return the info "Error" and the result is the message you want, if, vc want to return the message that the system itself generates, takes that phrase that I put in the result "It was not possible to capture the user’s data!." and put like this:

$e->getMessage()

Then just treat where you will consume, you can even validate it, plus the less so:

if(res.info == 'success'){
   $pegando_os_dados = res.result;
}else(res.info == 'error'){
   $error = res.result;
}

Dai vc shows the error the way you want it. Vlw.

2

App/Exception/Handler.php

I think this way you can do it, take a test there!

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception))
    {
        if ($exception->getStatusCode() == 404)
            return response(['exception'=>$exception], 404);

        if ($exception->getStatusCode() == 500)
            return response(['exception'=>$exception], 500);
    }

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

Browser other questions tagged

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