how to disable laravel 5.4 default error handler - php

I am currently working on a laravel project. I need to redirect all error pages to 404 page not found page.
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
switch ($exception->getStatusCode()) {
// not authorized
case '403':
return \Response::view('404',array(),403);
break;
// not found
case '404':
return \Response::view('404',array(),404);
break;
// internal error
case '500':
return \Response::view('404',array(),500);
break;
default:
return $this->renderHttpException($exception);
break;
}
} else {
return parent::render($request, $exception);
}
return parent::render($request, $exception);
}
Is there anyway to redirect error page to 404 page?. Also the validation errors are not displaying in this code(Redirecting to 404 when validation errors occurs). I am using the version 5.4.

Its Bug of Laravel 5.4 modified on laravel 5.5
https://github.com/laravel/framework/pull/18481
change file vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php
if (! $this->isHttpException($e) && config('app.debug')) {
return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
}
if (! $this->isHttpException($e)) {
return \Response::view('404',array(),500);
}
return $this->toIlluminateResponse($this->renderHttpException($e), $e);

How about:
if ($this->isHttpException($exception)) {
abort(404);
}

Create a directory in resources/views/errors
In this directory create files
404.blade.php for 404 error.
500.blade.php for 400 error.
403.blade.php for 403 error.
These views will be automatically rendered.
for aborting application you can use abort(404)
Hope this helps.

check if the code below is in "handler.php"
"use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;"
and check error resource file.
( https://laracasts.com/discuss/channels/general-discussion/how-do-i-create-a-custom-404-error-page )
and you can use abort function in your handler

Related

how to show error message if route not found in laravel 5.2

If I change route name from url then how can I show the error message in larvel 5.2.
Suppose I am showing users list using url lara.local.com/users and I change the route like lara.local.com/userswwwww. In that case how to show error message.
It will throw 404 Not Found. To display a custom view while a URL not found create a file named 404.blade.php in your resources/views/errors/ directory. Whatever you write on that file it will be displayed. No need to do anything else. Laravel will handle the rest.
You can use exception handler for handle route not found errors. Update app\Exception\Handler.php like
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if ($this->isHttpException($e))
{
if($e->getStatusCode()===404 || $e->getStatusCode()===405)
{
return response()->view('errors.not-found', [], 404);
}
return $this->renderHttpException($e);
}
return parent::render($request, $e);
}

Laravel 5: Use 301 instead of 302

How can I update my Laravel app to use the 301 error code when redirecting instead of the default 302 that Laravel is currently using?
For example, in my routes.php I use the redirect() function to set the error code 301:
return redirect('URL_GOES_HERE/', 301);
But I have many redirects happening in the app. Is there a way to simply change the default 302 to be 301 across all redirects?
Redirector defining 302 as a default value
here it is a full reference about Redirector.php
you can override it
Here you check error response code
app/Exceptions/Handler.php
public function render($request, Exception $e)
{
// If response code 404 then do this
if($e->getStatusCode() == 404)
{
return redirect()->to('/error');
}
// If response code 301
if($e->getStatusCode() == 301)
{
return redirect()->to('/do');
}
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect('/')->with('message', 'Sorry, your session seems to have expired. Please login again.');
}
return parent::render($request, $e);
}

404 Error Handling in Laravel 5.2.15

I am asking this question because I did not get reply after adding my comment in this question
laravel routing and 404 error
In the above answer, we can see below code to be used in filters.php
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
But, I think we don't have filters.php in latest version. Can somebody suggest better way to handle 404 error?
You don't need to do that anymore. Don't include that. What you do is put a view file (your 404 error view) called 404.blade.php in your resources/views/errors folder and Laravel will handle 404 errors for you.
take a look
http://www.jeffmould.com/2016/05/25/laravel-5-error-handling/
I just change this line App/Exceptions/Handler.php file.
public function render($request, Exception $e)
{
// the below code is for Whoops support. Since Whoops can open some security holes we want to only have it
// enabled in the debug environment. We also don't want Whoops to handle 404 and Validation related exceptions.
if (config('app.debug') && !($e instanceof ValidationException) && !($e instanceof HttpResponseException))
{
/******************here I changed**********************/
# return $this->renderExceptionWithWhoops($e);
return response()->view('errors.404', [], 404);
}
// this line allows you to redirect to a route or even back to the current page if there is a CSRF Token Mismatch
if($e instanceof TokenMismatchException){
return redirect()->route('index');
}
// let's add some support if a Model is not found
// for example, if you were to run a query for User #10000 and that user didn't exist we can return a 404 error
if ($e instanceof ModelNotFoundException) {
return response()->view('errors.404', [], 404);
}
// Let's return a default error page instead of the ugly Laravel error page when we have fatal exceptions
if($e instanceof \Symfony\Component\Debug\Exception\FatalErrorException) {
return \Response::view('errors.500',array(),500);
}
// finally we are back to the original default error handling provided by Laravel
if($this->isHttpException($e))
{
switch ($e->getStatusCode()) {
// not found
case 404:
return \Response::view('errors.404',array(),404);
break;
// internal error
case 500:
return \Response::view('errors.500',array(),500);
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
/******************here I changed**********************/
#return parent::render($request, $e);
}
if (config('app.debug') && !($e instanceof ValidationException) && !($e instanceof HttpResponseException))
{

Show a 404 page if route not found in Laravel 5.1

I am trying to figure out to show 404 page not found if a route is not found. I followed many tutorials, but it doesn't work.
I have 404.blade.php in \laravel\resources\views\errors
Also in handler.php
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
// redirect to form an example of how i handle mine
return redirect($request->fullUrl())->with(
'csrf_error',
"Opps! Seems you couldn't submit form for a longtime. Please try again"
);
}
/*if ($e instanceof CustomException) {
return response()->view('errors.404', [], 500);
}*/
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
If I enter wrong URL in browser, it returns a blank page. I have
'debug' => env('APP_DEBUG', true),
in app.php.
Can anyone help me how to show a 404 page if route is not found? Thank you.
I recieved 500 errors instead of 404 errors. I solved the problem like this:
In the app/Exceptions/Handler.php file, there is a render function.
Replace the function with this function:
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
switch ($e->getStatusCode()) {
// not authorized
case '403':
return \Response::view('errors.403',array(),403);
break;
// not found
case '404':
return \Response::view('errors.404',array(),404);
break;
// internal error
case '500':
return \Response::view('errors.500',array(),500);
break;
default:
return $this->renderHttpException($e);
break;
}
} else {
return parent::render($request, $e);
}
}
You can then use views that you save in views/errors/404.blade.php, and so on.
> The abort method will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
abort(403, 'Unauthorized action.');
is your app_debug set to true? if that is the case, Laravel will throw the error with backtrace for debugging purposes, if you change the value to false, Laravel will show the default 404 page in the errors folder. That being said you can choose to use abort at any time you want. at the controller level or at the route level, it is totally up to you.
ie
Route::get('/page/not/found',function($closure){
// second parameter is optional.
abort(404,'Page not found');
abort(403);
});
#tester.Your problem has already been solved, try the command below in composer:
php artisan view:clear
Then try once more with an unknown URL. Because I have also faced the same error before.
There is no need for you to check the error type and manually render the 404 view. Laravel already knows to render the view with the HTTP error code that was thrown (404 = resources/views/errors/404.blade.php). Get rid of the extra check and it should work fine.
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
// redirect to form an example of how i handle mine
return redirect($request->fullUrl())->with(
'csrf_error',
"Opps! Seems you couldn't submit form for a longtime. Please try again"
);
}
return parent::render($request, $e);
}
I use the following in app/Exceptions/Handler.php (Laravel 5.2):
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof \ReflectionException OR $e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) //Si la ruta no existe, mostar view 404.
return response(view('errors.404'), 404);
return parent::render($request, $e);
}
And it looks like this:img
In apache you could be able to put this code in .htaccess file at your main directory and make sure that change AllowOverride Directive to all in httpd confg file
ErrorDocument 404 the\path\to\404.blade.php
In config folder app.php change the following code
'debug' => env('APP_DEBUG', true),
In App->Exception->Handler.php Replace Render Function With Below Code
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException)
{
return response()->view('errors.404', [], 404);
}
if ($exception instanceof \ErrorException) {
return response()->view('errors.500', [], 500);
}
else {
return parent::render($request, $exception);
}
return parent::render($request, $exception);
}
If you want to redirect to the 404 page if the route is not found..
Route::fallback(function () {
return view('404');
});

laravel 5 custom 404

This is driving me crazy. I'm working with Laravel 5 and it appears that the docs for 4.2 and generating 404 pages does not work.
First, there is no global.php so I tried putting the following in routes.php:
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
This results in an error "method missing() not found"
Debug is set to false.
I've searched and searched but so far have found no information on setting 404 pages in Laravel 5. Would appreciate any help.
Go to resources/views/errors and create a 404.blade.php file with what you want on your 404 page and Laravel takes care of the rest.
if you want to have some global solution, you can do changes in /app/Exceptions/Handler.php by adding code bellow
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
$statusCode = $e->getStatusCode();
switch ($statusCode) {
case '404':
return response()->view('layouts/index', [
'content' => view('errors/404')
]);
}
}
return parent::render($request, $e);
}
In Laravel 5 you could simply put a custom 404.blade.php under resources/views/errors and that's it. For other errors like 500 you could try the following in your app/Exeptions/Handler.php:
public function render($request, Exception $e)
{
if ( ! config('app.debug') && ! $this->isHttpException($e)) {
return response()->view('errors.500');
}
return parent::render($request, $e);
}
And do the same for 500 HTTP Exeptions
I like the case statement approach but it has some issues going levels deep.
However, this catches all errors:
Route::any('/{page?}',function(){
return View::make('errors.404');
})->where('page','.*');
Laravel 5 already has a pre-defined render method(line 43) under app/Exceptions/Handler.php. Simply insert the redirection code before parent::render. Like so,
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException)
{
$e = new NotFoundHttpException($e->getMessage(), $e);
}
//insert this snippet
if ($this->isHttpException($e))
{
$statusCode = $e->getStatusCode();
switch ($statusCode)
{
case '404': return response()->view('error', array(), 404);
}
}
return parent::render($request, $e);
}
Note: My view is under resources/views. You can somehow put it anywhere else you want.
Lavavel 5.8
Create a file in resources/views/errors/404.blade.php and add this code.
#extends('errors::minimal')
#section('title', __('Not Found'))
#section('code', '404')
#if($exception)
#section('message', $exception->getMessage())
#else
#section('message', __('Not Found'))
#endif
Then in your controller you can use:
abort(404, 'Whatever you were looking for, look somewhere else');
I was looking for an answer to something else but thought I'd help in case someone else is looking for this.
run the command php artisan vendor:publish
you will see all publishable files. type in the number for laravel-errors
the error files are then published to resources/views/errors folder
set for Particulier prefix and with custom condition
Route::fallback(function(Request $request) {
if($request->is('practitioner/*')) {
return response()->view('errors.practitioner-404', [], 404);
} else if( $request->is('patient/*') ) {
return response()->view('errors.patient-404', [], 404);
} else {
abort(404);
}
});
You need to create errors folder inside resources/views and place your 404.blade.php file inside errors folder.
It will do the work. you do not need to edit handler.php file inside App/Exception folder.

Categories