php – Laravel 7 email exceptions broke after Symfony 5 update-ThrowExceptions

Exception or error:

I’ve upgraded to Laravel 7.1 and now with Symfony 5 these classes no longer exist:

use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;

I used them in my app\Exceptions\Handler.php file to send email notifications when exceptions re thrown and they worked well in Laravel 6, but broke when I upgrade from 6.x to 7.1.2 which also upgraded to Symfony 5.

I replaced the aforementioned classes with these:

use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;

and then replaced this:

$e = FlattenException::create($exception);
$handler = new SymfonyExceptionHandler();
$html = $handler->getHtml($e);

with this:

$e = FlattenException::create($exception);
$handler = new HtmlErrorRenderer();
$content = $handler->getBody($e);

which works, but now instead of getting the debug content in the email like I used to, I instead get a more basic error message as it would be intended for the public.

You can see examples of the different formats here:
https://symfony.com/doc/current/controller/error_pages.html

I’m sure there is something simple I’m missing, but I haven’t yet figured out how to get it to send me the detailed exception data like I used to get prior to the upgrade.

Any suggestions?

How to solve:

Below is the code I ended up using to get the results I wanted in the exception notification email. The primary piece I was missing earlier is that I wasn’t passing a true value into the HtmlErrorRender class to raise the debug flag. The corrected line is shown here:

new HtmlErrorRenderer(true);

Here is the complete code I am using now for the app/Exceptions/Handler.php file

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Log;
use Throwable;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        if ($this->shouldReport($exception)) {
            $this->sendEmail($exception); // sends an email
        }
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {  //https://gist.github.com/jrmadsen67/bd0f9ad0ef1ed6bb594e
            return redirect()
                ->back()
                ->withInput($request->except('password'))
                ->with('errorMessage', 'This form has expired due to inactivity. Please try again.');
        }

        return parent::render($request, $exception);
    }

    /**
     * Sends an email to the developer about the exception.
     *
     * @return void
     */
    public function sendEmail(Throwable $exception)
    {
        try {
            $e = FlattenException::create($exception);
            $handler = new HtmlErrorRenderer(true); // boolean, true raises debug flag...
            $css = $handler->getStylesheet();
            $content = $handler->getBody($e);

            \Mail::send('emails.exception', compact('css','content'), function ($message) {
                $message
                    ->to('youremailhere@gmail.com')
                    ->subject('Exception: ' . \Request::fullUrl())
                ;
            });
        } catch (Throwable $ex) {
            Log::error($ex);
        }
    }
}

The $css and $content are passed into the view at resources/views/emails/exception.blade.php. The code I have in that file is as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <style>{!! $css ?? '' !!}</style>
    </head>
    <body>
        {!! $content ?? '' !!}
    </body>
</html>

Answer´╝Ü

To get the complete response as html simply use:

$html = ExceptionHandler::convertExceptionToResponse($e);

Here is a the complete Handler.php Code

<?php

namespace App\Exceptions;

use Log;
use Mail;
use Exception;
use Throwable;
use App\Mail\ErrorNotification;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;


class Handler extends ExceptionHandler
{

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ModelNotFoundException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Throwable $e)
    {
        if ($this->shouldReport($e)) {
            $this->sendEmail($e);
        }

        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Throwable $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        return parent::render($request, $e);
    }


    public function sendEmail(Throwable $e)
    {
        try {

            $html = ExceptionHandler::convertExceptionToResponse($e);

            Mail::to('youremailhere@gmail.com')->send(new ErrorNotification($html));

        } catch (Exception $ex) {
            Log::error($ex);
        }
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *