From the documentation it says we can catch all 404 like so:
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
And we can also do things like:
App::abort(404);
App::abort(403);
All 404 gets handled by the App::missing
All other errors gets handled by:
App::error(function( HttpException $e)
{
//handle the error
});
But the question is How do i handle each of the error like if its a 403 I will display this if its a 400 I will display another error
Short answer: if your custom App::error function does not return a value, Laravel will handle it. Check the docs
Code sample for custom error views and/or logic:
App::error(function(Exception $exception, $code){
// Careful here, any codes which are not specified
// will be treated as 500
if ( ! in_array($code,array(401,403,404,500))){
return;
}
// assumes you have app/views/errors/401.blade.php, etc
$view = "errors/$code";
// add data that you want to pass to the view
$data = array('code'=>$code);
// switch statements provided in case you need to add
// additional logic for specific error code.
switch ($code) {
case 401:
return Response::view($view, $data, $code);
case 403:
return Response::view($view, $data, $code);
case 404:
return Response::view($view, $data, $code);
case 500:
return Response::view($view, $data, $code);
}
});
The above snippet could be inserted in app/start/global.php after the default Log::error handler, or better yet in the boot method of a custom service provider.
EDIT: Updated so the handler only processes codes you specify.
Related
In my controller, I used the method firstOrFail() for a database query with Eloquent. When in debug mode, I get a Laravel error message with the content Illuminate\Support\ItemNotFoundException.
However, I'd like to return a redirect() or mabye back() instead of showing this error screen. How can I do that?
use php try catch, to override the behaviour of error catching,
try {
// your functional code
} catch (Illuminate\Support\ItemNotFoundException $exception ) {
//your redirect command , the code here will be executed if there is an exception with type ItemNotFoundException
}
if you want to catch all errors, you need to use the General Exception class which is the parent of all Exceptions
try {
// your functional code
} catch (\Exception $exception) {
//your redirect command , the code here will be executed if there is any exception
}
if you want to get the exception message to log it or any customization , you can use the method : getMessage() , in our case will be $exception->getMessage()
Instead of firstOrFail() use first() and use condition to redirect back, for example:
$item = Item::where('slug', $slug)->first();
if (! $item) {
return redirect()->back();
}
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
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))
{
When i get this error:
QueryException in Connection.php line 620: SQLSTATE[23000]: Integrity
constraint violation: 1062 Duplicate entry
can i handle it with my own flash error message instead of:
Whoops, looks like something went wrong
You have two ways to handle exceptions and show a custom response:
1) Let the framework handle them for you:
If you don't handle exceptions by yourself, Laravel will handle them in the class:
App\Exceptions\Handler
In the render method you can intercept the renderning of all the exceptions the framework rises.
So, if you want to do something in particular when a specific exception rises, you can modify that method this way:
public function render($request, Exception $e)
{
//check the type of the exception you are interested at
if ($e instanceof QueryException) {
//do wathever you want, for example returining a specific view
return response()->view('my.error.view', [], 500);
}
return parent::render($request, $e);
}
2) Handle the exceptions by yourself:
You can handle exceptions by yourself, with try-catch blocks. For example in a controller's method:
try
{
//code that will raise exceptions
}
//catch specific exception....
catch(QueryException $e)
{
//...and do whatever you want
return response()->view('my.error.view', [], 500);
}
The main difference between the two cases is that in case 1 you are defining a general, application-wide approach to handle specific exceptions.
On the other hand, in case 2, you can define exception hadling in specific points of your application
This is work with me fine
if ($e instanceof \PDOException) {
$dbCode = trim($e->getCode());
//Codes specific to mysql errors
switch ($dbCode)
{
case 23000:
$errorMessage = 'my 2300 error message ';
break;
default:
$errorMessage = 'database invalid';
}
return redirect()->back()->with('message',"$errorMessage");
}
Before app starts I need to check a few things and if the go wrong load error page. All is done in App:before filter except the return as it just doesn’t work. Is somehow possible to stop the app from before filter?
I would try by throwing an exception. You could define something like a BootstrapException. Then you throw it if something goes wrong in App::before():
App::before(function ($request) {
// do checks
if (/* checks failed */) {
throw new BootstrapException;
}
});
After that, you can listen to that exception (e.g.) in start/global.php where there is already an App::error() call:
App::error(function (BootstrapException $exception, $code) {
return Response::view('errorpage', [], $code);
});
I'm not sure about this, but put your App::error() before the catch all App::error(function (Exception $exception, $code) { ... }); that is defined in start/global.php, because every exception is derived from Exception so your BootstrapException would be caught by that error handling call and not by your specific error handling code.