Does anyone know how to make the application return in a general way anyexception using a response in Json format with the respective HTTP error and a descriptive message of the error occurred, without performing any type of redirection to the
time of occurrence?
This is an example of what I want
{
"errors": [],
"exception":
"Illuminate\Database\Eloquent\ModelNotFoundException",
"file":
"/var/www/project/vendor/laravel/framework/src/Illuminate/Database/Eloqu
ent/Builder.php",
"line": 598,
"message": "No query results for model
[App\Models\API\ModelName].",
"statusCode": 404
}
I was trying to do this from App/Exception/Handler.php
<?php
namespace AppExceptions;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
$Status = array('msg'=>$e);
return response ($Status,$e);
});
}
}
2
Answers
Create on Trait GlobalExceptionHandler in app/Traits directory
And in App/Exception/Handler.php use Trait to render the exception
If you require as per the example
There is some modification can be done to achieve it
in Handler class add below method
In above render method
return parent::render($request, $exception);
is default