Reputation: 103
I'm using Laravel 5.5
and am new to it. As concerns error handling, I found that Laravel has many facades and features built-in, however, I seem not to have wrapped my head around all the features it provides (to originally make my life easier).
What I want is that whenever an error occurs (i.e. exception's thrown), Laravel shall redirect the user to the previous page and display an error message (not the error itself, you don't want users to be able to see this in production; I thought of something like 'Error occurred'
).
I included a display for errors in all of my views, so I just need to pass (via POST I suppose) an array message
with title
and message
, as well as style
(using Bootstrap styles, e.g. danger
, warning
, success
). Ideally, the exception is logged somewhere so I'm able to reproduce errors later on.
My current solution is devoid of Laravel's nice features since I just try-catch
everywhere and redirect to a specific page (I've chosen to be 'the right one' for this error). Also, this oppresses the original error.
What is the best approach for my desire?
Upvotes: 4
Views: 6230
Reputation: 103
This is my solution which excludes the validation and thus supports Laravel's built-in validation error, whereas every other error is differently displayed:
Log::error($exception->getMessage());
if($exception instanceof \Illuminate\Validation\ValidationException)
return parent::render($request, $exception);
return redirect(URL::previous())->withErrors(['Error', 'Unknown Error']);
Thanks to @jedrzej.kurylo who posted a solution on where to start. The code above shall be used under /App/Exceptions/Handler.php
, function render
.
Upvotes: 1
Reputation: 40909
Have a look at Laravel's exception handler: https://laravel.com/docs/5.5/errors#the-exception-handler
You can achieve what you want by implementing custom render()
method that would return a redirect response.
The
render
method is responsible for converting a given exception into an HTTP response that should be sent back to the browser.
Upvotes: 4