Laravel 5 handle all errors - laravel

Not sure how this is done in Laravel 5. In 4 you could add in App::error(function(Exception $exception, $code){} block to the routes.php file, and it would serve as a blanket exception handler. I get how it works in Laravel 5 where you add handling for individual exceptions and custom exceptions, which is great - but is there a sort of "Catch all" handling mechanism as well?

You would probably need to have to customize the render() method of App\Exceptions\Handler, as stated here : http://laravel.com/docs/5.0/errors#handling-errors
You can edit the app/Exceptions/Handler.php to do the job :
public function render($request, Exception $e)
{
//Your code here
return view('error');
}

Related

Handle module not found in laravel 7 routing

let's say I have some
Route::get('/path/{model}', 'Controller#method');
In the case of mysite.com/path/1 & no Model#1, I getting 404 which is default Laravel behavior
I want to handle (basically, redirect to another named route) "NoModelFound" for specific group of routes / specific route
As this route exists, Route::fallback or Route::any will not trigger here.
I know there is a Route()->missing method in Laravel 8, but I have Laravel 7 and can't update.
Also, in the best way, I search for solutions within routes ( web.php )
Is any solution for this? thanks in advance
You can globally handle exception in App\Exceptions\Handler class. If you really and i mean really want to be specific about handling ModelNotFoundException for only certain routes then you can do some thing like
// Exception Handle class
public function render($request, Exception $exception)
{
if(
$request->is('*path/') && // or string match
$exception instanceof ModelNotFoundException
){
redirect()->to('where-ever');
}
}
If you just want to redirect user whenever ModelNotFoundException occurs then you could do this,
// Exception Handle class
public function render($request, Exception $exception)
{
if(
$exception instanceof ModelNotFoundException
){
redirect()->to('where-ever');
}
}
Another way would be to use a middleware and check for certain model, if it doesnt exist, then redirect the user. Depends on what you are trying to do. You can find more information here
https://laravel.com/docs/8.x/middleware
https://laravel.com/docs/8.x/errors#the-exception-handler

Laravel logs doesn't report some things

I have an error, like the error below:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: PUT.
I know that's a error from routes, but I can't see anything in laravel.log.
Here I saw that Laravel doesn't report some things, but my Exceptions/Handler.php file is like this:
protected $dontReport = [
//
];
How do I report everything in laravel.log?
Laravel 6
All exceptions are handled by the App\Exceptions\Handler class. Use the report method to log exceptions.
public function report(Throwable $exception)
{
Log::error($exception); // add this line here
parent::report($exception);
}
See more from docs here

Method render() is not being called when custom Laravel exception is thrown from view composer

Edited:
I have a custom exception with render method which is being called when I throw it e.g. from controller, but not being called when I throw it in View composer.
So when I do something like that
public function compose(View $view)
{
throw new CustomException();
}
and put dd() to exception render method
public function render()
{
dd('render is called');
}
I get no result.
If I log my exception directly, finds out that first the CustomException being thrown, then as the result I see ErrorException.
I found a place where it being thrown.
\Illuminate\View\Engines\CompilerEngine::handleViewException
protected function handleViewException(Exception $e, $obLevel)
{
$e = new ErrorException($this->getMessage($e), 0, 1, $e->getFile(), $e->getLine(), $e);
parent::handleViewException($e, $obLevel);
}
I didn't found any mentions in Laravel docs about that case.
I found a tread on github with the same issue: https://github.com/laravel/framework/issues/24658
So the question is, is this expected? Is there any adequate way to avoid this behaviour?
Edit
So, as you know, any exception during view compilation is intercepted and rethrown as ErrorException or as FatalThrowableError.
What you can do is intercept ErrorException and check if ($e->getPrevious() instanceof \CustomException) if so, you do your code, else, let the handler continue.
So I've found working solution for myself.
I've extended CompilerEngine and added additional processing in order to not throw ErrorException when I don't want to.
The important thing is - your resulting Exception must be inherited from ErrorException. Otherwise you will face multiple calls to \App\View\Engines\CompilerEngine::handleViewException which can break your logic and write multiple log entities to your log file.

How to redirect another page instead of redirecting to abort 403 error page in Laravel 5.4

My question is whenever there is a 403 error I should redirect to my own custom page or show the flash message(on the same page) something like that.How can I achieve this in Laravel?.
You can use app/Exceptions/Handler.php for this
public function render($request, Exception $e)
{
if ($e->getStatusCode() == 403) {
return redirect('yourpage'); // this will be on a 403 exception
}
return parent::render($request, $e); // all the other exceptions
}
You can create a view for specific HTTP error codes. If you set up a Blade template at resources/views/errors/403.blade.php, it will get used for all 403 error responses.
Source
Alternatively you can set up a custom exception handler for 403 responses if you need something more involved. I found a good example of this here.
you can make you own page in inside the view .resources/views/errors/yourblade.blade.php
after that just return your page to that page.
You can use app/Exceptions/Handler.php for this as Thomas Moors stated above or you can use a try catch for basic error handling.
try {
do Something //
}
catch (Exception $e) {
//log error in log file or dv
return redirect->('home');
}

Design 500 error page only for production

I'm looking for a modern (Laravel 5.4) way to display custom 500 error page only for HTTP (non ajax/fetch) response. I read some threads but each response looks like a trick or is outdated. There is probably something to modify in \App\Exceptions\Handler, but I did not find the "right way".
Is there a simple way to display a specific page on fatal error (uncatched, returning 500) in Laravel 5.4?
In other words, when I have a syntax error on one of my controller, it displays "Whoops something went wrong" with some HTML and 500 error code. I would like to display something else, with the same rules as default behavior (ideally only for HTML browser, not for ajax/fetch, etc.).
EDIT: only in production environment.
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable.
https://laravel.com/docs/5.4/errors#custom-http-error-pages
From the selected "best answer" of this thread: https://laracasts.com/discuss/channels/general-discussion/custom-error-page-er500
You could modify \App\Exceptions\Handler::render():
public function render($request, Exception $exception)
{
if (config('app.debug') && !$this->isHttpException($exception)) {
$exception = new \Symfony\Component\HttpKernel\Exception\HttpException(500);
}
return parent::render($request, $exception);
}
Your exception will be reported in the logs as usually, but woops page will be replaced by your 500.blade.php view.
Sometimes you have to catch the specific exception in order to render the error view. in Laravel 5.4 you can do this by editing the report() method in the App\Exceptions\Handler class
public function report(Exception $exception)
{
if ($exception instanceof CustomException) {
// here you can log the error and return the view, redirect, etc...
}
return parent::report($exception);
}

Resources