Laravel 5.2 - customize error "Whoops, looks like something went wrong" - laravel

How can I change the error page "Whoops, looks like something went wrong."? I want to show my page 404 inside errors folder
my handler is simple:
public function render($request, Exception $e)
{
return parent::render($request, $e);
}

I assume you're already inside of app/Exceptions/Handler.php
public function render($request, Exception $e)
{
return response()->view('errors.custom');
}

change that to
public function handle($request)
{
try
{
return parent::handle($request);
}
catch(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e)
{
return response()->view('Viewname', [], 404);
}
catch (Exception $e)
{
$this->reportException($e);
return $this->renderException($request, $e);
}
}

Access the handler.php in the App\Exception folder and change the default code to the code below.
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('404', [], 404);
}
if ($exception->getStatusCode() == 403) {
return response()->view('403', [], 403);
}
}
return parent::render($request, $exception);
}

Related

I want to redirect to login page when page expired(419) display

I added this code in handler.php
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login_page');
}
but when session destroyed, it does not redirect to login page.
I think you are doing it in a wrong section so in your Handler.php class create a report method
Laravel 7 and higher
public function report(Throwable $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login_page');
}
}
Laravel 6 and below
public function report(Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login_page');
}
}
In Laravel 8 or higher, go to app/Exceptions edit Handler.php and update the register method as follows-
public function register()
{
$this->renderable(function (\Exception $e) {
if ($e->getPrevious() instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->route('login');
};
});
}
in return redirect()->route('login'); change you login to your login route.

How to Redirect the page if the url has a different parameters or the route doesn't exist? in laravel

how to redirect the page if the route doesn't exist like
'sitename.me/asdasdas'
because when I'm trying to do this
the NotFoundHttpException will show up.
please help me thanks
You can change the app/Exceptions/Handler.php for this purpose. Replace the render() and unauthenticated() function with the following.
public function render($request, Exception $exception) {
if ($this->isHttpException($exception)) {
switch ($exception->getStatusCode()) {
// not found
case 404:
return redirect()->guest(your redirect url));
break;
// internal error
case '500':
return redirect()->guest(your redirect url));
break;
default:
return $this->renderHttpException($exception);
break;
}
} else {
return parent::render($request, $exception);
}
}
protected function unauthenticated($request, AuthenticationException $exception) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(your redirect url);
}
To redirect to external domains, use the following:
return redirect()->away('http://sitename.me/asdasdas');
To redirect to an internal URI, use:
return redirect('admin/dashboard');
To redirect to an application route, use:
return redirect()->route('admin.dashboard');
For further reference, have a look at the responses (redirects) documentation.
let me explain some details i have faced, Laravel throw common exception throw Handler.php file in app/Exceptions folder. In this file we have report function that throw common exception using render function.
public function report(Exception $exception)
{
if ($exception instanceof \League\OAuth2\Server\Exception\OAuthServerException){
$this->render(null,$exception);
} else {
parent::report($exception);
}
}
Above is an report function that throw any exception to render function specified below
public function render($request, Exception $exception)
{
if($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException){
// return Helper::responseJson(null,'header','Page Not Found',404);
} else if ($exception instanceof ScopeHandler) {
return Helper::responseJson(null,'header','Unauthorized',401);
} else if ($exception instanceof \League\OAuth2\Server\Exception\OAuthServerException){
return Helper::responseJson(null,'token','Unauthorized',401);
} else if ($exception instanceof ModelNotFoundException) {
// return Helper::responseJson(null,'header','Model Not Found',404);
} else if ($exception instanceof \Illuminate\Database\QueryException){
// return Helper::responseJson(null,'header','Query Exception',400);
} else if ($exception instanceof \Swift_TransportException){
return Helper::responseJson(null,'header','Mail send Exception',400);
}else if ($exception instanceof ConnectionFailedException){
return Helper::responseJson(null,'header','Connection Exception',400);
}
/* else if($exception instanceof \Symfony\Component\Debug\Exception\FatalErrorException){
return Helper::responseJson(null,'header','PHP config Exception',400);
} */
return parent::render($request, $exception);
}
the above example of render function we used for throw exception using json format. we can redirect to specific page or we can do any functionality when these error thrown.

Laravel always return the error bag of an Validation error in json

I'm developing an api that should also provide messages about the validation problems.
When "hardcoding" validators I'm doing something like this
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
this works nice - however I want a "generic" solution to basically catch all ValidationExceptions and do the same as above.
I already tried to play around in the render function of Handler.php
public function render($request, Exception $exception)
{
$message = $exception->getMessage();
if (is_object($message)) {
$message = $message->toArray();
}
if ($exception instanceof ValidationException) {
return response()->json($message, 400);
}
...
}
However I can't find a proper way of returning the actual relevant data that I want
It's kinda dumb - actually laravel already provided what I want. Handler extends ExceptionHandler which does:
public function render($request, Exception $e)
{
$e = $this->prepareException($e);
if ($e instanceof HttpResponseException) {
return $e->getResponse();
} elseif ($e instanceof AuthenticationException) {
return $this->unauthenticated($request, $e);
} elseif ($e instanceof ValidationException) {
return $this->convertValidationExceptionToResponse($e, $request);
}
return $this->prepareResponse($request, $e);
}
and convertValidationExceptionToResponse :
if ($e->response) {
return $e->response;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput(
$request->input()
)->withErrors($errors);
So exactly what I wanted
public function render($request, Exception $exception)
{
if ($request->wantsJson() && (str_contains('api/v1/register', $request->path())) || (str_contains('api/v1/login', $request->path())) ) {
$errors = null ;
if($exception->validator){
$errors = $exception->validator->errors();
}
return response()->json([
'status' => 422,'success'=> false,'message'=>''. $exception->getMessage() ,'error'=> "" . $errors
], 422);
}
return parent::render($request, $exception);
}

Redirect to homepage if route doesnt exist in Laravel 5

/** Redirect 404's to home
*****************************************/
App::missing(function($exception)
{
// return Response::view('errors.missing', array(), 404);
return Redirect::to('/');
});
I have this code in my routes.php file. I am wondering how to redirect back to the home page if there is a 404 error. Is this possible?
For that, you need to do add few lines of code to render method in app/Exceptions/Handler.php file which looks like this:
public function render($request, Exception $e)
{
if($this->isHttpException($e))
{
switch ($e->getStatusCode())
{
// not found
case 404:
return redirect()->guest('home');
break;
// internal error
case '500':
return redirect()->guest('home');
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
}
I just want to add a suggestion for cleaning it up a bit more. I'd like to credit the accepted answer for getting me started. In my opinion however since every action in this function will return something, the switch and else statement create a bit of bloat. So to clean it up just a tad, I'd do the following.
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
if ($e->getStatusCode() == 404)
return redirect()->guest('home');
if ($e->getStatusCode() == 500)
return redirect()->guest('home');
}
return parent::render($request, $e);
}
you may Just do this :
open : app\Exceptions\Handler.php
in handler.php you can replace this code :
return parent::render($request, $exception);
by this : return redirect('/');
it works good
,example :
public function render($request, Exception $exception)
{
return redirect('/');
//return parent::render($request, $exception);
}

Laravel 5 Error Handling

I am using Laravel 5 and I am trying to make custom 404 page and custom Exception handling, but I can't figure out where to put my code. Some time ago there was an ErrorServiceProvider that no longer exists. Can anyone give me some pointers?
EDIT: I saw they have added a Handler class in the App/Exception folder but that still seems not the right place to put it because it does not follow at all the laravel 4.2 App::error, App::missing and App::fatal methods. Anyone has any ideas?
Use app/Exceptions/Handler.php render method to achieve that. L5 documentation http://laravel.com/docs/5.0/errors#handling-errors
public function render($request, Exception $e)
{
if ($e instanceof Error) {
if ($request->ajax()) {
return response(['error' => $e->getMessage()], 400);
} else {
return $e->getMessage();
}
}
if ($this->isHttpException($e)) {
return $this->renderHttpException($e);
} else {
return parent::render($request, $e);
}
}
Here is how to customize your error page while complying with the APP_DEBUG setting in .env.
app/Exceptions/Handler.php
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
if (env('APP_DEBUG'))
{
return parent::render($request, $e);
}
return response()->view('errors.500', [], 500);
}
}

Resources