How do I create custom view for errors on Lumen? I tried to create resources/views/errors/404.blade.php, like what we can do in Laravel 5, but it doesn't work.
Errors are handled within App\Exceptions\Handler. To display a 404 page change the render() method to this:
public function render($request, Exception $e)
{
if($e instanceof NotFoundHttpException){
return response(view('errors.404'), 404);
}
return parent::render($request, $e);
}
And add this in the top of the Handler.php file:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Edit: As #YiJiang points out, the response should not only return the 404 view but also contain the correct status code. Therefore view() should be wrapped in a response() call passing in 404 as status code. Like in the edited code above.
The answer by lukasgeiter is almost correct, but the response made with the view function will always carry the 200 HTTP status code, which is problematic for crawlers or any user agent that relies on it.
The Lumen documentation tries to address this, but the code given does not work because it is copied from Laravel's, and Lumen's stripped down version of the ResponseFactory class is missing the view method.
This is the code which I'm currently using.
use Symfony\Component\HttpKernel\Exception\HttpException;
[...]
public function render($request, Exception $e)
{
if ($e instanceof HttpException) {
$status = $e->getStatusCode();
if (view()->exists("errors.$status")) {
return response(view("errors.$status"), $status);
}
}
if (env('APP_DEBUG')) {
return parent::render($request, $e);
} else {
return response(view("errors.500"), 500);
}
}
This assumes you have your errors stored in the errors directory under your views.
It didn't work for me, but I got it working with:
if($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return view('errors.404');
}
You might also want to add
http_response_code(404)
to tell the search engines about the status of the page.
Related
In Laravel, how can i translate the error shown in production mode like "500 Internal Server Error", to other language (locale) ?
You may be need custom error view, for implemention you need to create 500.blade.php in errors folder of views. and then design it by your need. But remember that server errors like 500 wont render views. For that you may try to edit app/Exceptions/Handler.php's render function to this :
public function render($request, Exception $e) {
// 404 page when a model is not found
if ($e instanceof ModelNotFoundException) {
return response()->view('errors.404', [], 404);
}
if ($this->isHttpException($e)) {
return $this->renderHttpException($e);
} else {
// Custom error 500 view on production
if (app()->environment() == 'production') {
return response()->view('errors.500', [], 500);
}
return parent::render($request, $e);
}
}
Share if this helps you, it didnt tested by me. But it should work
Update
Above code may show 500 for validation errors, so check out this one
public function render($request, Exception $e) {
$exception = \Symfony\Component\Debug\Exception\FlattenException::create($e);
$statusCode = $exception->getStatusCode($exception);
if (env('APP_DEBUG') == FALSE && $statusCode == 500 && $e instanceof ValidationException != TRUE) {
return response()->view('errors.500', [], 500);
} else {
return parent::render($request, $e);
}
}
Internally, all the error pages render text with i18n support.
Keep in mind that for further customization other than translating messages, you can still publish the error views and customize them to suit your needs with this artisan command:
php artisan vendor:publish --tag=laravel-errors
You should refer to this paragraph about localization using translation strings as keys to create the required json files.
The keys you need to override are defined in the default blade error pages you can find on github
Imagine you want to override the 500 error message.
Find all the usages of the __ (double underscore) function in the 500.blade.php file as well as in the layout files.
The provided parameter would become the key you will use to override the message in the json file.
Example
For instance, given the 500.blade.php file contents:
#extends('errors::minimal')
#section('title', __('Server Error'))
#section('code', '500')
#section('message', __('Server Error'))
The corresponding json translation file could be defined as:
{
"Server Error": "This is my custom message that will override the default one!"
}
If you still have doubts, just ask for clarifications in the comments.
I'm looking for a way to catch all possible errors and redirect all types of errors to 1 page.
My current code in /Exceptions/Handler.php:
if ($this->isHttpException($exception)) {
$statusCode = $exception->getStatusCode();
switch ($statusCode) {
case '404':
return response()->view('layouts/404');
}
}
Problem is that ErrorException (E_NOTICE) types (which are caused by possible bugs in the code) aren't redirected to the 404 page. These errors end up on the 'Woops something went wrong' page.
I basically am trying to make every type of error end up on my custom error page.
All attempts end up on white pages.
What am I not seeing?
Well, to do what you're asking for you should go to App\Exceptions\Handler.php and there, you need to modify the render method:
public function render($request, Exception $exception)
{
abort(404);
}
But I insist, this is a terrible idea, you should catch the Exceptions that your app may get and show the error message to the user in a clean way, for example:
try{
//... your fancy code here
}catch(Exception $e){
// return with the message error $e->getMessage()
}
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');
}
I want to handle all the non available routes and redirect them to my 503.blade view. i.e whenever user enters URL like //localhost:8000/adbkjabd or //localhost:8000/anything-they-like i want to handle them and show them 503 view. In my render() function. It is not redirecting me to the 503 page and still says in the same page with errors.
public function render($request, Exception $e)
{
if ($e instanceof NotFoundHttpException) {
// normal 503 view page feedback
return response()->view('errors.503', [], 404);
}
return parent::render($request, $e);
}
Am i having a wrong understanding of this or am i making any logical errors ?
Say you have a simple resource route like this:
Route::resource('overview', 'OverviewController');
And hit routes which you know don't exist. For example:
/overview/sdflkjdsflkjsd
/overview/sdflkjdsflkjsd/edit
Which in my case throws Trying to get property of non-object error from my view (as no resource is found)
I looked into adding 'Regular Expression Parameter Constraints' from the docs, but it looks like these are not available for resource routes either (plus don't really fix the problem).
I'm looking for a way to throw a single exception for this kind of thing, which I can then handle once, rather than add logic to each action (or at least the show and edit actions).. if possible.
EDIT After looking around github, I found the exception in the Symphony repo here. Is there a way I can hook into it?
Since you're getting a Trying to get property of non-object error, I assume you're fetching the resource via YourModel::find();
I'd suggest you use YourModel::findOrFail() instead. Then, you'd be getting a specific type of exception called ModelNotFoundException. Just register an error handler for this.
For instance,
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
UPDATE: This would actually go into render() method inside the app/Exceptions/Handler.php file in Laravel 5.1, and of course the code would utilize the passed $e parameter instead.
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException)
{
return \Response::make('Not Found', 404);
}
return parent::render($request, $e);
}