in my laravel 10, I had a appExceptionsHandler.php
class to render a json response when something try to access an invalid api endpoint or to render the default framework 404 page when something try to access a non-existent non-api page:
<?php
namespace AppExceptions;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
protected $dontReport = [];
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
public function register()
{
$this->reportable(function (Throwable $e) {});
}
public function render($request, Throwable $e)
{
if ($request->is('api/*')) {
return response()->json(['error' => 404, 'message' => 'route_not_found'], 404);
} else {
return parent::render($request, $e);
}
}
}
I’ve updated the framework to laravel 11 and moved the excetions to bootstrapapp.php
using the ->withExceptions()
method:
<?php
use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationExceptions;
use IlluminateFoundationConfigurationMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
commands: __DIR__ . '/../routes/console.php',
api: __DIR__ . '/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->api(append: [
AppHttpMiddlewareApiResponse::class
])
->alias([
'auth' => AppHttpMiddlewareAuthenticate::class
]);
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (Throwable $e, IlluminateHttpRequest $request) {
if ($request->is('api/*')) {
return response()->json(['error' => 404, 'message' => 'route_not_found'], 404);
} else {
abort(404);
}
});
})
->create();
the thing is I wish to use something like the return parent::render($request, $e);
from laravel 10, since it return the default 404 page of the framework. The abort(404)
in laravel 11 return a generic 500 error with no render at all.
I’ve tried to instantiate the IlluminateFoundationExceptionsHandler
, but its constructor needs a container which I don’t know how to provide one.
How can I render the default 404 error page in laravel 11 using the ->withExceptions()
method?
thx in advance