From 27753e903bd58fc0824d645e13b6d7bbfee5042e Mon Sep 17 00:00:00 2001 From: James Collins Date: Thu, 27 Jul 2023 20:58:38 +1000 Subject: [PATCH] added exception handling --- app/Exceptions/Handler.php | 46 ++++++++++++++++-- app/Mail/ExceptionMail.php | 55 ++++++++++++++++++++++ resources/views/emails/exception.blade.php | 10 ++++ 3 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 app/Mail/ExceptionMail.php create mode 100644 resources/views/emails/exception.blade.php diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index b35c316..7d5c9bb 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -2,13 +2,17 @@ namespace App\Exceptions; -use App\Enum\HttpResponseCodes; -use Exception; +use App\Mail\ExceptionMail; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Throwable; use PDOException; -use Symfony\Component\HttpKernel\Exception\HttpException; +use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer; +use Exception; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Mail; +use Symfony\Component\ErrorHandler\Exception\FlattenException; class Handler extends ExceptionHandler { @@ -58,8 +62,42 @@ class Handler extends ExceptionHandler } }); + $this->renderable( + function (Throwable $exception, $request) { + if ($exception instanceof \Illuminate\Session\TokenMismatchException) { + return redirect() + ->back() + ->withInput($request->except('password')) + ->with('errorMessage', 'This form has expired due to inactivity. Please try again.'); + } + } + ); + + $this->reportable(function (Throwable $e) { - // + if ($this->shouldReport($e) === true) { + $this->sendEmail($e); + } }); } + + + public function sendEmail(Throwable $exception) + { + try { + $e = FlattenException::create($exception); + $handler = new HtmlErrorRenderer(true); + $css = $handler->getStylesheet(); + $content = $handler->getBody($e); + + Mail::send('emails.exception', compact('css', 'content'), function ($message) { + $message + ->to('youremailhere@gmail.com') + ->subject('Exception Generated') + ; + }); + } catch (Throwable $ex) { + Log::error($ex); + } + } } diff --git a/app/Mail/ExceptionMail.php b/app/Mail/ExceptionMail.php new file mode 100644 index 0000000..0dbf5c3 --- /dev/null +++ b/app/Mail/ExceptionMail.php @@ -0,0 +1,55 @@ + + */ + public function attachments(): array + { + return []; + } +} diff --git a/resources/views/emails/exception.blade.php b/resources/views/emails/exception.blade.php new file mode 100644 index 0000000..70957b5 --- /dev/null +++ b/resources/views/emails/exception.blade.php @@ -0,0 +1,10 @@ + + + + + + + + {!! $content ?? '' !!} + + \ No newline at end of file