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?