Error Handling
Laravel Error Handling
Categories:
Force to return json format on the unauthenticated auth user
// app/Exceptions/Handler.php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
protected function unauthenticated($request, AuthenticationException $exception)
{
return response()->json(['message' => $exception->getMessage()], 401);
}
}
Route::get('/user', function () {
//
})->middleware('auth:api');
Force to return json format on the 404 or 500 https status
// app/Exceptions/Handler.php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
protected function renderHttpException(HttpExceptionInterface $exception)
{
$status_code = $exception->getStatusCode();
$response_data = [
'status_code' => $status_code,
'message' => $exception->getMessage(),
];
return response()->json($response_data, $status_code, [], JSON_UNESCAPED_UNICODE);
}
}
abort(404, 'Not Found');