I could resolve it, for anyone who needs it. The key was to clone the $exceptions->handler BEFORE to personalize the render function to avoid infinite bucle.
->withExceptions(function (Exceptions $exceptions) {
$handler = clone $exceptions->handler;
$exceptions->render(function (Throwable $e, Request $request) use ($handler) {
$previousValue = config("app.debug");
config(["app.debug" => true]);
$htmlError = $handler->render($request, $e)->getContent();
config(["app.debug" => $previousValue]);
//Code that sends the email
});
});
Now, this works if you have Ignition, because is a custom error reporting sistem but if not, this generates the ugly symphony error page. This is because on loading laravel it checks if app.debug is true or false and then loads some things about error reporting in the FoundationServiceProvider so, we need to "reload" them this way each time we change the app debug value:
->withExceptions(function (Exceptions $exceptions) {
$handler = clone $exceptions->handler;
$exceptions->render(function (Throwable $e, Request $request) use ($handler) {
$fsp = new \Illuminate\Foundation\Providers\FoundationServiceProvider(app());
$previousValue = config("app.debug");
config(["app.debug" => true]);
$fsp->register();
$htmlError = $handler->render($request, $e)->getContent();
config(["app.debug" => $previousValue]);
$fsp->register();
//Code that sends the email
});
});
Maybe is not the best optimized way, i'm all open to any more simple suggestions.
Thank you very much