Handle Laravel QueryException and show custom error page using XAMPP - laravel

I'm locally developing a Laravel website using XAMPP. To make the site works, I obviously have to turn on the Apache service and it does work indeed. What I want to be able to do is to handle the case when the apache server is down and show my error message. I mean, if I purposely turn off Apache, I receive this error Exception:
Illuminate\Database\QueryException
SQLSTATE[HY000] [2002] Connection refused.
(SQL: select * from `users` where `email` = test#yahoo.it limit 1)
This is the image: https://pasteboard.co/JegwA2Y.png
Here comes my question. How can I show for example one of my custom error pages instead of this default Laravel QueryException? Where to catch the exception?
Even though my app is not on production mode, I'd still like to show the errors properly.
Thanks!

You must change render method in App\Exceptions\Handler class. You can read details in documentation.
Sample Code:
public function render($request, Throwable $exception)
{
// Custom render.
if ($exception instanceof QueryException) {
return response()->view('errors.query', [], 500);
}
// Add extra custom render.
if ($exception instanceof ModelNotFoundException) {
return response()->view('errors.not_found', [], 500);
}
// Default render.
return parent::render($request, $exception);
}

Related

Laravel Spatie MultiTenanct noCurrentTenant Exception Handle

I'm making a multitenancy system and I'm facing problem when trying to handle the NoCurrentTenant Exception..
I'm using spatie multitenancy
I'm expecting that when there is NoCurrentTenant exception is thrown , it should redirect to login route. But that is not happening.
Below is my Exception Hander register method.
public function register() {
$this->reportable(function (NoCurrentTenant $e) {
return redirect('/saml2/laraveltestidp/login');
});
}
But even after multiple tries it still shows below error only
Spatie\Multitenancy\Exceptions\NoCurrentTenant
The request expected a current tenant but none was set.

Translate Production error on Laravel 5.8

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.

How to set a default error page to users in Laravel

Is there a way in Laravel to show a nice error page to users if an error occurred while they were browsing ?
It could be a general message without any details, such as "Something went wrong, please try again in a few seconds".
If something is there, I would like to know where to start.
If I understood your question you don't want error with image of code where is error.
If that is a problem you can set in your .env debug to false 'debug' => false.
Then you need to clear cache: php artisan config:cache.
And just restart your php artisan serve.
This should work. Please let me know if that isn't what do you want.
Good luck!
You can display a custom message by edit app\Exceptions\Handler.php
for example, if the error code is 500, you can return a custom view like this:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 500) {
return response()->view('partials.error_500', [], 500);
}
return parent::render($request, $exception);
}
or you can check if the error is instanceof anything like this:
if ($exception instanceof ErrorException) {
abort(500);
or return view(...)
and so on ...
}

prevent Lumen from showing default 500 Internal Server Error on API responses

I have a Route defined as:
$app->post('api/v1/Subject','SubjectController#createSubject');
And in the Controller I have the following code:
public function createSubject(Request $request){
$Subject = Subject::create($request->all());
return response()->json($Subject);
}
Now, when someone sends incorrect data, it triggers a Query Exception - "SQLSTATE[23000]: Integrity constraint violation:" which is understood.
However, what I want is: I want do not want Lumen to send its own default Error Page in API Response. I want to capture this error event and send my own customized response. How can I do that?
Since I could not find a solution, I tried to add my own view at: /resources/views/errors/500.blade.php but Lumen is even ignoring this template. Please help. Ideally, I would want to capture this error event and send my own customized response.
EDIT:
Lumen was reporting two exceptions - PDOException and QueryException at the 500 error response. So, to get a custom error message, I put the following code in side function render() in app\Exceptions\Handler:
public function render($request, Exception $e)
{
if($e instanceof PDOException){
return response('It is my Custom response for PDOException that caused 500 error response.');
}
if($e instanceof QueryException){
return response('It is my Custom response for QueryException that cuased 500 error response.');
}
return parent::render($request, $e);
}

Design 500 error page only for production

I'm looking for a modern (Laravel 5.4) way to display custom 500 error page only for HTTP (non ajax/fetch) response. I read some threads but each response looks like a trick or is outdated. There is probably something to modify in \App\Exceptions\Handler, but I did not find the "right way".
Is there a simple way to display a specific page on fatal error (uncatched, returning 500) in Laravel 5.4?
In other words, when I have a syntax error on one of my controller, it displays "Whoops something went wrong" with some HTML and 500 error code. I would like to display something else, with the same rules as default behavior (ideally only for HTML browser, not for ajax/fetch, etc.).
EDIT: only in production environment.
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable.
https://laravel.com/docs/5.4/errors#custom-http-error-pages
From the selected "best answer" of this thread: https://laracasts.com/discuss/channels/general-discussion/custom-error-page-er500
You could modify \App\Exceptions\Handler::render():
public function render($request, Exception $exception)
{
if (config('app.debug') && !$this->isHttpException($exception)) {
$exception = new \Symfony\Component\HttpKernel\Exception\HttpException(500);
}
return parent::render($request, $exception);
}
Your exception will be reported in the logs as usually, but woops page will be replaced by your 500.blade.php view.
Sometimes you have to catch the specific exception in order to render the error view. in Laravel 5.4 you can do this by editing the report() method in the App\Exceptions\Handler class
public function report(Exception $exception)
{
if ($exception instanceof CustomException) {
// here you can log the error and return the view, redirect, etc...
}
return parent::report($exception);
}

Resources