Internet not available exception in Laravel 5.2 - laravel

I was trying to open Sandbox paypal page from my Laravel application and faced below issue
This issue came when internet connection was not available. Like we face 404 issue...for that we have 404 blade in View folder.
Is there any way to handle this exception so that we can show a user friendly page to user that Please check your internet connection
It doesn't not works when I write below code:
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
return response()->view('errors.InternetConnection');
}
but it works when I write
if ($e instanceof \PayPal\Exception\PayPalConnectionException) {
\App::abort(404);
}
I created a new blade called InternetConnection in error folder

You can listen for this exception in App\Exceptions\Handler#render. Just add this:
if ($e instanceof PayPalConnectionException) {
return response()->view('errors.404', [], 404);
}

Yes, you can! (https://laravel.com/docs/5.1/errors#the-exception-handler)
in your App\Exceptions\Handler:
...
public function render($request, Exception $e)
{
if ($e instanceof PayPalConnectionException) {
//my paypal exception
return response()->view('errors.payPalConnectionError', [], 404);
}
return parent::render($request, $e);
}

This will work:-
you need to create a folder named errors if not already exist in views and place blade file named 404.blade.php in it. and put your error template for 404 error in this blade. laravel will automatically use it when ever a 404 error will occur.

In your app/Exceptions/Handler.php edit render method as:
public function render($request, Exception $e)
{
if($e instanceof ValidationException) return response()->view('errors.abc');
return parent::render($request, $e);
}
Remember Don't forget to USE the Exception in your Handler.php
Like I am showing abc view for ValidationException So I am adding this line in my Handler.php class
use Illuminate\Validation\ValidationException;
Otherwise this won't work.

Related

Laravel localization for custom error pages

I have custom error pages e.g. resources/views/errors/404.blade.php everything is working just fine but the localization is not working for error pages. If I change website language the error pages still show in default language I tried in many way but its not working, Can anyone please help me make this work thanks in advance.
I try to make it work via exception handler but don't know how to do that. I can apply language middleware is someone can tell me where is default routes for error pages.
You can also redirect to other pages in App\Exceptions\Handler.php. You can also assign using App::setLocale(). Like this:
public function render($request, Throwable $exception)
{
App::setLocale('en_GB');
/** #var \Symfony\Component\HttpKernel\Throwable $e */
$e = $exception;
$statusCode = $e->getStatusCode();
return $this->isHttpException($exception) && $statusCode == 404 ?
response()->view('frontend.pages.404') :
parent::render($request, $exception);
}
Open app/exceptions/handler.php
find render function paste here
don't for get import this trait
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function render($request, Exception $e)
{
if($request->hasCookie('language')) {
// Get cookie
$cookie = $request->cookie('language');
// Check if cookie is already decrypted if not decrypt
$cookie = strlen($cookie) > 2 ? decrypt($cookie) : $cookie;
// Set locale
app()->setLocale($cookie);
}
if($e instanceof NotFoundHttpException) {
return response()->view('errors.404', [], 404);
}
return parent::render($request, $e);
}
thank you guys a little discussion with you guys fixed my problem I get the session's locale value in exception handler that worked for me I am answering it may be can help some one else. Below are the thing I did in App/Exception/Handler.php
use Session;
public function render($request, Throwable $exception)
{
app()->setLocale(Session::get('locale'));
return parent::render($request, $exception);
}
also i moved
\Illuminate\Session\Middleware\StartSession::class,
from web group to global group in kernal.php

customize ExceptionHandler in findOrFail error message

Good morning all,
Laravel v7.+
I made a
$user = User::findOrFail($id);
on my controller, it works well but when I have no result it sends me to a 404 page.
I would like to be able to do a return back with error message.
Some are talking about try catch.
Do you have any other solution to optimize?
Thank you, good day, stay home!
If you are having this issue in a single Controller only, you can use try catch
If you need a more general solution, you can work with the exception render method (https://laravel.com/docs/master/errors#render-method) on the ModelNotFoundException
public function render($request, Throwable $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $exception);
}
Alternative to try/catch
$user = User::find($id);
if(!$user){
return redirect()->back()->with(['error' => 'Error message']);
}
... your other logic here

How to redirect users to another page with session messages while error occuring

I want to redirect users to admin page when any error occuring about the thujohn/twitter package. It throws Runtimeexception..
So I add couple code handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof \RuntimeException) {
return redirect()->route('admin.panel')
->with('message', 'Please try again later..')
->with('message_type','warning');
} else {
return parent::render($request, $exception);
}
}
But when I say that, it redirects user at all exceptions even at 404 errors or Trying to get property of non-object erros.. How can I fix this ? I want to redirect user for just relevant error
Or is there any way to do redirect user with condition like below.
if($exception->code == 436){
// it says member has protected access. I can't use it code property outside of the exception class
return redirect()->route('admin.panel')
->with('message', 'Specific error message')
->with('message_type','warning');
}
First of all go to Exceptions/Handler.php.
Here you can develope your exeptions.
This is my example on QueryException (you need to find by dd() your exception and its code):
use Illuminate\Database\QueryException; // REMEMBER TO USE PROPER INSTANCE
public function render($request, Exception $exception)
{
//dd($exception); <-- here you can catch and check type od exception
switch(true) {
case $exception instanceof QueryException:
if($exception->getCode() == '23000') {
return redirect(
route('get.dashboard.index')
)->with('warning', 'No record in database);
}
break;
}
}

Having a controller on 404 urls using Laravel 5

I need to have a custom controller triggered when user hits a not-existing url or when I programmatically force an App::abort(404).
How can I do it?
My 404 views need some data, and a simple blade View (or a ViewComposer) is not enough.
Thanks
PS catch-all urls is not functional, because they don't catch programmatically launched 404.
Edit the render function of App\Exceptions\Handler class and add something about 404 here:
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
// Do what you want...
// You can even use the $request variable
}
Full example:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
echo 'hello from 404 renderer';
dd($request); // Or you can a view.
}
return parent::render($request, $exception);
}
Try to return a redirect() to your custom Controller instead of a response() from the Handler's render() method if the exception is 404. You can retrieve the the page requested from the $request then right ?
Here is the sample:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
return redirect(route('route.to.custom.controller'))->with('request', $request);
}
return parent::render($request, $exception);
}
Hope that will help, cheers !

Laravel: how to prevent a MethodNotAllowedHttpException in RouteCollection.php when someone access a post-route without giving post parameters?

Laravel: how to prevent a MethodNotAllowedHttpException in RouteCollection.php when someone access a post-route without giving post parameters?
When i define a post route its only accessable by a post request. If i call the url normaly in a browser, it throws an exception. how to prevent this?
Anyone can do a request to any of your routes using a method that isn't allowed. You can make a view for the exception in the resources/views/errors folder. Laravel comes with an error page for the HTTP status code 503 (Service Unavailable Error) by default.
The HTTP status code for the MethodNotAllowedHttpException is 405, so making a view called 405.blade.php will cause Laravel to present that view instead of the MethodNotAllowedHttpException message.
This should do the job
This will catch all errors like, MethodNotAllowed or 404(page not found) or ModelNotFound or TokenMissMatch and redirect to any route you desire with proper error!
Handler.php
public function render($request, Exception $e){
if ($e instanceof ForbiddenException) {
return redirect()->route('name')->withErrors(['error' => $e->getMessage()]);
}
return parent::render($request, $e);
}
Or just for Method not allowed
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
if ($e instanceof MethodNotAllowedHttpException) {
return redirect()->route('name')->withErrors(['error' => $e->getMessage()]);
}
Use Route::any() or Route::match()
Example:
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('foo', function () {
//
});
I tried the match and any methods but they were not what I needed.
This is what I did:
1- Added the default error handler in the Base controller.
2- Called the error manually for each forbidden HTTP METHOD.
Then, on the BaseController:
adding a file "405.blade.php" into your "resources/views/errors" will prevent the MethodNotAllowedHttpException page from showing up again.
For laravel 9, i solved it this way, you can change the exception to be caught. Make sure to include it at the top:
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
And:
Handler.php
/**
* Register the exception handling callbacks for the application.
*
* #return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
$this->renderable(function (MethodNotAllowedHttpException $e, $request) {
return abort(404, "page not found");
});
}

Resources