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?
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?
– Crazy
I hadn’t realized the
try-catch
... But no, you wouldn’t treat him atcatch
but it would return the error message anyway. Reviewing your code again, I believe it is not capturing the exception to beException
and not\Exception
. Anyway, I would recommend not usingtry-catch
in cases like yours, and yes, create a custom exception or return the error as in the examples I gave.– Vinicius Lourenço
@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.
– Vinicius Lourenço
was just that, missed the Catch Bar inside... Solved!!! Thanks brother!
– Crazy