As I create a REST API, I want all 404 and 403 errors displayed as JSON. When I try to return a message, the message is empty, but the error codes are usually displayed. Does anyone know what I'm doing wrong? I'm using PHP 8 and Laravel 9.
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
public function register()
{
$this->renderable(function (Throwable $e, $request) {
$request->headers->set('Accept', 'application/json');
if ($e instanceof HttpExceptionInterface && $request->wantsJson()) {
$code = $e->getStatusCode() ?: 400;
$message = $e->getMessage() ?: 'Invalid Request.';
return response(['success' => false, 'message' => $message], $code);
}
});
$this->reportable(function (Throwable $e) {
//
});
}
}
I think you have to return response in json format like
and if you gonna try your api in postman do not forget to add
in headers.