I’m trying to create an app on Laravel 4 beta but I can’t debug it because it doesn’t show any error, display_errors
is on, error_reporting
is E_ALL
and debug => true
(config/app.php
). When I try to do an error on public/index.php
it shows a parse error, but when I do it on the router it just shows a blank page (White screen of death). How can I fix this?
Thank you
Mykola
3,3276 gold badges23 silver badges39 bronze badges
asked Jan 28, 2013 at 18:14
5
@Matanya — have you looked at your server logs to see WHAT the error 500 actually is? It could be any number of things
@Aladin — white screen of death (WSOD) can be diagnosed in three ways with Laravel 4.
Option 1: Go to your Laravel logs (app/storage/logs) and see if the error is contained in there.
Option 2: Go to you PHP server logs, and look for the PHP error that is causing the WSOD
Option 3: Good old debugging skills — add a die(‘hello’) command at the start of your routes file — then keep moving it deeper and deeper into your application until you no longer see the ‘hello’ message. Using this you will be able to narrow down the line that is causing your WSOD and fix the problem.
answered Feb 26, 2013 at 14:22
LaurenceLaurence
58.2k20 gold badges169 silver badges210 bronze badges
3
I had a problem with the white screen after installing a new laravel instance. I couldn’t find anything in the logs because (eventually I found out) that the reason for the white screen was that app/storage wasn’t writable.
In order to get an error message on the screen I added the following to the public/index.php
try {
$app->run();
} catch(Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
After that it was easy to solve the problem.
answered Jan 22, 2014 at 15:09
cw24cw24
1,5932 gold badges19 silver badges31 bronze badges
1
Go to
app/config/app.php
and
set ‘debug’ => true,
answered Oct 23, 2014 at 14:24
John DoeJohn Doe
2212 silver badges2 bronze badges
Following the good advice by @The Shift Exchange I looked at the error_log and indeed managed to solve to problem. it was simply a permissions issue:
Tue Feb 26 11:22:20 2013] [error] [client 127.0.0.1] PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/Users/matanya/Sites/indgo/app/start/../storage/logs/log-apache2handler-2013-02-26.txt" could not be opened: failed to open stream: Permission denied' in /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:71nStack trace:n#0 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(77): Monolog\Handler\StreamHandler->write(Array)n#1 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\RotatingFileHandler->write(Array)n#2 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Logger.php(217): Monolog\Handler\AbstractProcessingHandler->handle(Array)n#3 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Logger.php(281): Monolog\Logger->addRecord(400, Object(ErrorException), Array)n#4 [internal function]: Monolog\Logger->addError(Object(ErrorException))n#5 /Users/matanya/Sites/in in /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 71
Once I used chmod
to apply less stringent permissions, all went back to normal.
However, I’m not sure that it answers the OP’s question, as he was getting a blank screen rather than a server error.
answered Feb 26, 2013 at 9:47
MatanyaMatanya
6,1857 gold badges47 silver badges79 bronze badges
1
Inside config folder open app.php
Change
'debug' => false,
to
'debug' => true,
Ashish Kakkad
23.4k12 gold badges100 silver badges135 bronze badges
answered Aug 31, 2015 at 13:39
Further to @cw24’s answer • as of Laravel 5.4
you would instead have the following amendment in public/index.php
try {
$response = $kernel->handle(
$request = IlluminateHttpRequest::capture()
);
} catch(Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
And in my case, I had forgotten to fire up MySQL.
Which, by the way, is usually mysql.server start
in Terminal
answered Apr 15, 2017 at 0:24
GrantGrant
5,3202 gold badges37 silver badges46 bronze badges
In the Laravel root folder chmod the storage directory to 777
answered Nov 12, 2016 at 5:02
TheRealJAGTheRealJAG
1,85820 silver badges16 bronze badges
Maybe not on Laravel 4 this time, but on L5.2* I had similar issue:
I simply changed the ownership of the storage/logs
directory to www-data
with:
# chown -R www-data:www-data logs
PS: This is on Ubuntu 15 and with apache.
My logs
directory now looks like:
drwxrwxr-x 2 www-data www-data 4096 jaan 23 09:39 logs/
answered Jan 23, 2017 at 9:52
Just go to your app/storage/logs
there logs of error
available. Go to filename of today’s date time and you will find latest error
in your application.
OR
Open app/config/app.php
and change setting
'debug' => false,
To
'debug' => true,
OR
Go to .env
file to your application and change the configuratuion
APP_LOG_LEVEL=debug
answered Dec 25, 2017 at 2:40
Rahul HirveRahul Hirve
1,09913 silver badges20 bronze badges
Version
Error Handling
- Introduction
- Configuration
-
The Exception Handler
- Reporting Exceptions
- Exception Log Levels
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
-
HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
During local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler
class. This class contains a register
method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. However, you are free to log exceptions however you wish.
For example, if you need to report different types of exceptions in different ways, you may use the reportable
method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
When you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop
method when defining your reporting callback or return false
from the callback:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
Note
To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context
method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Exception Log Levels
When messages are written to your application’s logs, the messages are written at a specified log level, which indicates the severity or importance of the message being logged.
As noted above, even when you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application; however, since the log level can sometimes influence the channels on which a message is logged, you may wish to configure the log level that certain exceptions are logged at.
To accomplish this, you may define an array of exception types and their associated log levels within the $levels
property of your application’s exception handler:
use PDOException;
use PsrLogLogLevel;
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<Throwable>, PsrLogLogLevel::*>
*/
protected $levels = [
PDOException::class => LogLevel::CRITICAL,
];
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport
property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
use AppExceptionsInvalidOrderException;
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
InvalidOrderException::class,
];
Note
Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable
method of your exception handler.
The closure passed to the renderable
method should return an instance of IlluminateHttpResponse
, which may be generated via the response
helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
You may also use the renderable
method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException
. If the closure given to the renderable
method does not return a value, Laravel’s default exception rendering will be utilized:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register
method, you may define report
and render
methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(/* ... */);
}
}
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false
from the exception’s render
method to render the exception’s default HTTP response:
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Determine if the exception needs custom rendering...
return false;
}
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false
from the exception’s report
method:
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
// Determine if the exception needs custom reporting...
return false;
}
Note
You may type-hint any required dependencies of thereport
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a «page not found» error (404), an «unauthorized error» (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort
helper:
abort(404);
Custom HTTP Error Pages
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
view template. This view will be rendered 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 SymfonyComponentHttpKernelExceptionHttpException
instance raised by the abort
function will be passed to the view as an $exception
variable:
<h2>{{ $exception->getMessage() }}</h2>
You may publish Laravel’s default error page templates using the vendor:publish
Artisan command. Once the templates have been published, you may customize them to your liking:
php artisan vendor:publish --tag=laravel-errors
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php
template and a 5xx.blade.php
template in your application’s resources/views/errors
directory.
Ошибки и логирование
- Введение
-
Настройка
- Детализация ошибок
- Хранилище логов
- Коды серьёзности логов
- Пользовательская настройка Monolog
-
Обработчик исключений
- Метод Report
- Метод Render
-
HTTP-исключения
- Пользовательские страницы HTTP-ошибок
- Логгирование
Введение
Когда вы начинаете новый Laravel проект, обработка ошибок и исключений уже настроена для вас. Все происходящие в вашем приложении исключения записываются в журнал и отображаются пользователю в классе AppExceptionsHandler
. В этой документации мы подробно рассмотрим этот класс.
Для логгирования Laravel использует библиотеку Monolog, которая обеспечивает поддержку различных мощных обработчиков логов. В Laravel настроены несколько из них, благодаря чему вы можете выбрать между единым файлом журнала, ротируемыми файлами журналов и записью информации в системный журнал.
Настройка
Детализация ошибок
Параметр debug
в файле настроек config/app.php
определяет, сколько информации об ошибке показывать пользователю. По умолчанию этот параметр установлен в соответствии со значением переменной среды APP_DEBUG
, которая хранится в файле .env
.
Для локальной разработки вам следует установить переменную среды APP_DEBUG
в значение true
. В продакшн-среде эта переменная всегда должна иметь значение false
. Если значение равно true
, на продакшн-сервере, вы рискуете раскрыть важные значения настроек вашим конечным пользователям.
Хранилище логов
Изначально Laravel поддерживает запись журналов в единые файлы single
, в отдельные файлы для каждого дня daily
, в syslog
и errorlog
. Для использования определённого механизма хранения вам надо изменить параметр log
в файле config/app.php
. Например, если вы хотите использовать ежедневные файлы логов вместо единого файла, вам надо установить значение log
равное daily
в файле настроек app
:
'log' => 'daily'
Максимальное число ежедневных файлов логов
При использовании режима daily
Laravel по умолчанию хранит логи только за последние пять дней. Если вы хотите изменить число хранимых файлов, добавьте в файл app
значение для параметра log_max_files
:
'log_max_files' => 30
Коды серьёзности логов
При использовании Monolog сообщения в журнале могут иметь разные уровни серьёзности. По умолчанию Laravel сохраняет в журнал события всех уровней. Но на продакшн-сервере вы можете задать минимальный уровень серьёзности, который необходимо заносить в журнал, добавив параметр log_level
в конфиг app.php
.
После задания этого параметра Laravel будет записывать события всех уровней начиная с указанного и выше. Например, при log_level
равном error
будут записываться события error, critical, alert и emergency:
'log_level' => env('APP_LOG_LEVEL', 'error'),
В Monolog используются следующие уровни серьёзности — от меньшего к большему:
debug
,info
,notice
,warning
,error
,critical
,alert
,emergency
.
Пользовательская настройка Monolog
Если вы хотите иметь полный контроль над конфигурацией Monolog для вашего приложения, вы можете использовать метод приложения configureMonologUsing
. Вызов этого метода необходимо поместить в файл bootstrap/app.php
прямо перед тем, как в нём возвращается переменная $app
:
$app->configureMonologUsing(function ($monolog) {
$monolog->pushHandler(...);
});
return $app;
Обработчик исключений
Метод Report
Все исключения обрабатываются классом AppExceptionsHandler
. Этот класс содержит два метода: report
и render
. Рассмотрим каждый из них подробнее. Метод report
используется для занесения исключений в журнал или для отправки их во внешний сервис, такой как Bugsnag или Sentry. По умолчанию метод report
просто передаёт исключение в базовую реализацию родительского класса, где это исключение зафиксировано. Но вы можете регистрировать исключения как пожелаете.
Например, если вам необходимо сообщать о различных типах исключений разными способами, вы можете использовать оператор сравнения PHP instanceof
:
/**
* Сообщить или зарегистрировать исключение.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param Exception $exception
* @return void
*/
public function report(Exception $exception)
{
if ($exception instanceof CustomException) {
//
}
return parent::report($exception);
}
Игнорирование исключений заданного типа
Свойство обработчика исключений $dontReport
содержит массив с типами исключений, которые не будут заноситься в журнал. Например, исключения, возникающие при ошибке 404, а также при некоторых других типах ошибок, не записываются в журналы. При необходимости вы можете включить другие типы исключений в этот массив:
/**
* Список типов исключений, о которых не надо сообщать.
*
* @var array
*/
protected $dontReport = [
IlluminateAuthAuthenticationException::class,
IlluminateAuthAccessAuthorizationException::class,
SymfonyComponentHttpKernelExceptionHttpException::class,
IlluminateDatabaseEloquentModelNotFoundException::class,
IlluminateValidationValidationException::class,
];
Метод Render
Метод render
отвечает за конвертацию исключения в HTTP-отклик, который должен быть возвращён браузеру. По умолчанию исключение передаётся в базовый класс, который генерирует для вас отклик. Но вы можете проверить тип исключения или вернуть ваш собственный отклик:
/**
* Отображение HTTP-оклика для исключения.
*
* @param IlluminateHttpRequest $request
* @param Exception $exception
* @return IlluminateHttpResponse
*/
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $exception);
}
HTTP-исключения
Некоторые исключения описывают коды HTTP-ошибок от сервера. Например, это может быть ошибка «страница не найдена» (404), «ошибка авторизации» (401) или даже сгенерированная разработчиком ошибка 500. Для возврата такого отклика из любого места в приложении можете использовать хелпер abort
:
abort(404);
Хелпер abort
немедленно создаёт исключение, которое будет отрисовано обработчиком исключений. Или вы можете предоставить такой отклик:
abort(403, 'Unauthorized action.');
Пользовательские страницы HTTP-ошибок
В Laravel можно легко возвращать свои собственные страницы для различных кодов HTTP-ошибок. Например, для выдачи собственной страницы для ошибки 404 создайте файл resources/views/errors/404.blade.php
. Этот файл будет использован для всех ошибок 404, генерируемых вашим приложением. Представления в этой папке должны иметь имена, соответствующие кодам ошибок. Экземпляр HttpException
, созданный функцией abort
, будет передан в представление как переменная $exception
:
<h2>{{ $exception->getMessage() }}</h2>
Логгирование
Laravel обеспечивает простой простой уровень абстракции над мощной библиотекой Monolog. По умолчанию Laravel настроен на создание файла журнала в директории storage/logs
. Вы можете записывать информацию в журнал при помощи фасада Log
:
<?php
namespace AppHttpControllers;
use AppUser;
use IlluminateSupportFacadesLog;
use AppHttpControllersController;
class UserController extends Controller
{
/**
* Показать профиль данного пользователя.
*
* @param int $id
* @return Response
*/
public function showProfile($id)
{
Log::info('Showing user profile for user: '.$id);
return view('user.profile', ['user' => User::findOrFail($id)]);
}
}
Регистратор событий предоставляет восемь уровней логгирования, как описано в RFC 5424: emergency, alert, critical, error, warning, notice, info и debug.
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);
Контекстная информация
Также в методы логгирования можно передать массив контекстных данных:
Log::info('User failed to login.', ['id' => $user->id]);
Обращение к расположенному ниже экземпляру Monolog
В Monolog доступно множество дополнительных обработчиков для журналов. При необходимости вы можете получить доступ к расположенному ниже экземпляру Monolog, используемому в Laravel:
$monolog = Log::getMonolog();
Версия
Error Handling
- Introduction
- Configuration
-
The Exception Handler
- Reporting Exceptions
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
-
HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
During local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler
class. This class contains a register
method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. However, you are free to log exceptions however you wish.
For example, if you need to report different types of exceptions in different ways, you may use the reportable
method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
When you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop
method when defining your reporting callback or return false
from the callback:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
{tip} To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context
method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport
property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
use AppExceptionsInvalidOrderException;
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
InvalidOrderException::class,
];
{tip} Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable
method of your exception handler.
The closure passed to the renderable
method should return an instance of IlluminateHttpResponse
, which may be generated via the response
helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
You may also use the renderable
method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException
. If the closure given to the renderable
method does not return a value, Laravel’s default exception rendering will be utilized:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register
method, you may define report
and render
methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(...);
}
}
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false
from the exception’s render
method to render the exception’s default HTTP response:
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Determine if the exception needs custom rendering...
return false;
}
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false
from the exception’s report
method:
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
// Determine if the exception needs custom reporting...
return false;
}
{tip} You may type-hint any required dependencies of the
report
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a «page not found» error (404), an «unauthorized error» (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort
helper:
abort(404);
Custom HTTP Error Pages
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
view template. This view will be rendered 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 SymfonyComponentHttpKernelExceptionHttpException
instance raised by the abort
function will be passed to the view as an $exception
variable:
<h2>{{ $exception->getMessage() }}</h2>
You may publish Laravel’s default error page templates using the vendor:publish
Artisan command. Once the templates have been published, you may customize them to your liking:
php artisan vendor:publish --tag=laravel-errors
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php
template and a 5xx.blade.php
template in your application’s resources/views/errors
directory.
git b1b94b48f6779b37c412740a1806e6c1f4023a31
Обработка ошибок (Exception)
- Введение
- Конфигурирование
- Обработчик исключений
- Отчет об исключениях
- Игнорирование исключений по типу
- Отображение исключений
- Отчетные и отображаемые исключения
- HTTP-исключения
- Пользовательские страницы ошибок HTTP
Введение
Когда вы запускаете новый проект Laravel, обработка ошибок и исключений уже настроена для вас. Класс AppExceptionsHandler
– это то место, где все исключения, созданные вашим приложением, регистрируются и затем отображаются пользователю. В этой документации мы углубимся в этот класс.
Конфигурирование
Параметр debug
в конфигурационном файле config/app.php
определяет, сколько информации об ошибке фактически отобразится пользователю. По умолчанию этот параметр установлен, чтобы учесть значение переменной окружения APP_DEBUG
, которая содержится в вашем файле .env
.
Во время локальной разработки вы должны установить для переменной окружения APP_DEBUG
значение true
. Во время эксплуатации приложения это значение всегда должно быть false
. Если в рабочем окружении будет установлено значение true
, вы рискуете раскрыть конфиденциальные значения конфигурации конечным пользователям вашего приложения.
Обработчик исключений
Отчет об исключениях
Все исключения обрабатываются классом AppExceptionsHandler
. Этот класс содержит метод register
, в котором вы можете зарегистрировать свои отчеты об исключениях и замыкания рендеринга. Мы подробно рассмотрим каждую из этих концепций. Отчеты об исключениях используются для регистрации исключений или отправки их во внешнюю службу, например Flare, Bugsnag или Sentry. По умолчанию исключения будут регистрироваться в соответствии с вашей конфигурацией логирования. Однако вы можете регистрировать исключения как хотите.
Например, если вам нужно сообщать о различных типах исключений по-разному, вы можете использовать метод reportable
для регистрации замыкания, которое должно быть выполнено, когда необходимо сообщить об исключении конкретного типа. Laravel определит о каком типе исключения сообщает замыкание с помощью типизации аргументов:
use AppExceptionsInvalidOrderException;
/**
* Зарегистрировать замыкания, обрабатывающие исключения приложения.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
Когда вы регистрируете собственные замыкания для создания отчетов об исключениях, используя метод reportable
, Laravel по-прежнему регистрирует исключение, используя конфигурацию логирования по умолчанию для приложения. Если вы хотите остановить распространение исключения в стек журналов по умолчанию, вы можете использовать метод stop
при определении замыкания отчета или вернуть false
из замыкания:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
{tip} Чтобы настроить отчет об исключениях для переданного исключения, вы можете рассмотреть возможность использования отчетных исключений.
Глобальное содержимое журнала
Если доступно, Laravel автоматически добавляет идентификатор текущего пользователя в каждое сообщение журнала исключения в качестве контекстных данных. Вы можете определить свои собственные глобальные контекстные данные, переопределив метод context
класса AppExceptionsHandler
вашего приложения. Эта информация будет включена в каждое сообщение журнала исключения, написанное вашим приложением:
/**
* Получить переменные контекста по умолчанию для ведения журнала.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Контекст журнала исключений
Хотя добавление контекста в каждое сообщение журнала может быть полезно, иногда конкретное исключение может иметь уникальный контекст, который вы хотели бы включить в свои журналы. Определив метод context
для конкретного исключения вашего приложения, вы можете указать любые данные, относящиеся к этому исключению, которые должны быть добавлены в запись журнала исключения:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Получить контекстную информацию исключения.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
Помощник report
По желанию может потребоваться сообщить об исключении, но продолжить обработку текущего запроса. Помощник report
позволяет вам быстро сообщить об исключении через обработчик исключений, не отображая страницу с ошибкой для пользователя:
public function isValid($value)
{
try {
// Проверка `$value` ...
} catch (Throwable $e) {
report($e);
return false;
}
}
Игнорирование исключений по типу
При создании приложения будут некоторые типы исключений, которые вы просто хотите игнорировать и никогда не сообщать о них. Обработчик исключений вашего приложения содержит свойство $dontReport
, которое инициализируется пустым массивом. Ни о каких классах, добавленных в это свойство, никогда не будет сообщено; однако у них все еще может быть собственная логика отображения:
use AppExceptionsInvalidOrderException;
/**
* Список типов исключений, о которых не следует сообщать.
*
* @var array
*/
protected $dontReport = [
InvalidOrderException::class,
];
{tip} За кулисами Laravel уже игнорирует для вас некоторые типы ошибок, такие как исключения, возникающие из-за ошибок 404 HTTP «не найдено» или 419 HTTP-ответ, сгенерированный при недопустимом CSRF-токене.
Отображение исключений
По умолчанию обработчик исключений Laravel будет преобразовывать исключения в HTTP-ответ за вас. Однако вы можете зарегистрировать свое замыкание для отображения исключений конкретного типа. Вы можете сделать это с помощью метода renderable
обработчика исключений.
Замыкание, переданное методу renderable
, должно вернуть экземпляр IlluminateHttpResponse
, который может быть сгенерирован с помощью функции response
. Laravel определит, какой тип исключения отображает замыкание с помощью типизации аргументов:
use AppExceptionsInvalidOrderException;
/**
* Зарегистрировать замыкания, обрабатывающие исключения приложения.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
Вы также можете использовать метод renderable
чтобы переопределить отображение для встроенных исключений Laravel или Symfony, таких, как NotFoundHttpException
. Если замыкание, переданное методу renderable
не возвращает значения, будет использоваться отрисовка исключений Laravel по умолчанию:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Зарегистрировать замыкания, обрабатывающие исключения приложения.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Отчетные и отображаемые исключения
Вместо проверки типов исключений в методе register
обработчика исключений вы можете определить методы report
и render
непосредственно для ваших исключений. Если эти методы существуют, то они будут автоматически вызываться фреймворком:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Отчитаться об исключении.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Преобразовать исключение в HTTP-ответ.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(...);
}
}
Если ваше исключение расширяет исключение, которое уже доступно для визуализации, например встроенное исключение Laravel или Symfony, вы можете вернуть false
из метода render
исключения, чтобы отобразить HTTP-ответ исключения по умолчанию:
/**
* Преобразовать исключение в HTTP-ответ.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Определить, требуется ли для исключения пользовательское отображение...
return false;
}
Если ваше исключение содержит пользовательскую логику отчетности, которая необходима только при выполнении определенных условий, то вам может потребоваться указать Laravel когда сообщать об исключении, используя конфигурацию обработки исключений по умолчанию. Для этого вы можете вернуть false
из метода report
исключения:
/**
* Сообщить об исключении.
*
* @return bool|null
*/
public function report()
{
// Определить, требуется ли для исключения пользовательская отчетность ...
return false;
}
{tip} Вы можете указать любые требуемые зависимости метода
report
, и они будут автоматически внедрены в метод контейнером служб Laravel.
HTTP-исключения
Некоторые исключения описывают коды HTTP-ошибок с сервера. Например, это может быть ошибка «страница не найдена» (404), «неавторизованный доступ» (401) или даже ошибка 500, сгенерированная разработчиком. Чтобы создать такой ответ из любой точки вашего приложения, вы можете использовать глобальный помощник abort
:
Пользовательские страницы ошибок HTTP
Laravel позволяет легко отображать пользовательские страницы ошибок для различных кодов состояния HTTP. Например, если вы хотите настроить страницу ошибок для кодов HTTP-состояния 404, создайте файл resources/views/errors/404.blade.php
. Это представление будет отображено для всех ошибок 404, сгенерированных вашим приложением. Шаблоны в этом каталоге должны быть названы в соответствии с кодом состояния HTTP, которому они соответствуют. Экземпляр SymfonyComponentHttpKernelExceptionHttpException
, вызванный функцией abort
, будет передан в шаблон как переменная $exception
:
<h2>{{ $exception->getMessage() }}</h2>
Вы можете опубликовать стандартные шаблоны страниц ошибок Laravel с помощью команды vendor:publish
Artisan. После публикации шаблонов вы можете настроить их по своему вкусу:
php artisan vendor:publish --tag=laravel-errors
I’m trying to create an app on Laravel 4 beta but I can’t debug it because it doesn’t show any error, display_errors
is on, error_reporting
is E_ALL
and debug => true
(config/app.php
). When I try to do an error on public/index.php
it shows a parse error, but when I do it on the router it just shows a blank page (White screen of death). How can I fix this?
Thank you
Mykola
3,3276 gold badges23 silver badges39 bronze badges
asked Jan 28, 2013 at 18:14
5
@Matanya — have you looked at your server logs to see WHAT the error 500 actually is? It could be any number of things
@Aladin — white screen of death (WSOD) can be diagnosed in three ways with Laravel 4.
Option 1: Go to your Laravel logs (app/storage/logs) and see if the error is contained in there.
Option 2: Go to you PHP server logs, and look for the PHP error that is causing the WSOD
Option 3: Good old debugging skills — add a die(‘hello’) command at the start of your routes file — then keep moving it deeper and deeper into your application until you no longer see the ‘hello’ message. Using this you will be able to narrow down the line that is causing your WSOD and fix the problem.
answered Feb 26, 2013 at 14:22
LaurenceLaurence
58.2k20 gold badges169 silver badges210 bronze badges
3
I had a problem with the white screen after installing a new laravel instance. I couldn’t find anything in the logs because (eventually I found out) that the reason for the white screen was that app/storage wasn’t writable.
In order to get an error message on the screen I added the following to the public/index.php
try {
$app->run();
} catch(Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
After that it was easy to solve the problem.
answered Jan 22, 2014 at 15:09
cw24cw24
1,5932 gold badges19 silver badges31 bronze badges
1
Go to
app/config/app.php
and
set ‘debug’ => true,
answered Oct 23, 2014 at 14:24
John DoeJohn Doe
2212 silver badges2 bronze badges
Following the good advice by @The Shift Exchange I looked at the error_log and indeed managed to solve to problem. it was simply a permissions issue:
Tue Feb 26 11:22:20 2013] [error] [client 127.0.0.1] PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/Users/matanya/Sites/indgo/app/start/../storage/logs/log-apache2handler-2013-02-26.txt" could not be opened: failed to open stream: Permission denied' in /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:71nStack trace:n#0 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(77): Monolog\Handler\StreamHandler->write(Array)n#1 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\RotatingFileHandler->write(Array)n#2 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Logger.php(217): Monolog\Handler\AbstractProcessingHandler->handle(Array)n#3 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Logger.php(281): Monolog\Logger->addRecord(400, Object(ErrorException), Array)n#4 [internal function]: Monolog\Logger->addError(Object(ErrorException))n#5 /Users/matanya/Sites/in in /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 71
Once I used chmod
to apply less stringent permissions, all went back to normal.
However, I’m not sure that it answers the OP’s question, as he was getting a blank screen rather than a server error.
answered Feb 26, 2013 at 9:47
MatanyaMatanya
6,1857 gold badges47 silver badges79 bronze badges
1
Inside config folder open app.php
Change
'debug' => false,
to
'debug' => true,
Ashish Kakkad
23.4k12 gold badges100 silver badges135 bronze badges
answered Aug 31, 2015 at 13:39
Further to @cw24’s answer • as of Laravel 5.4
you would instead have the following amendment in public/index.php
try {
$response = $kernel->handle(
$request = IlluminateHttpRequest::capture()
);
} catch(Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
And in my case, I had forgotten to fire up MySQL.
Which, by the way, is usually mysql.server start
in Terminal
answered Apr 15, 2017 at 0:24
GrantGrant
5,3202 gold badges37 silver badges46 bronze badges
In the Laravel root folder chmod the storage directory to 777
answered Nov 12, 2016 at 5:02
TheRealJAGTheRealJAG
1,85820 silver badges16 bronze badges
Maybe not on Laravel 4 this time, but on L5.2* I had similar issue:
I simply changed the ownership of the storage/logs
directory to www-data
with:
# chown -R www-data:www-data logs
PS: This is on Ubuntu 15 and with apache.
My logs
directory now looks like:
drwxrwxr-x 2 www-data www-data 4096 jaan 23 09:39 logs/
answered Jan 23, 2017 at 9:52
Just go to your app/storage/logs
there logs of error
available. Go to filename of today’s date time and you will find latest error
in your application.
OR
Open app/config/app.php
and change setting
'debug' => false,
To
'debug' => true,
OR
Go to .env
file to your application and change the configuratuion
APP_LOG_LEVEL=debug
answered Dec 25, 2017 at 2:40
Rahul HirveRahul Hirve
1,09913 silver badges20 bronze badges
Laravel is one of the best web development frameworks.
But does it have any error handling feature?
Yes. There is a default feature that helps to debug by making Laravel show PHP errors in the browser.
At Bobcares, we often get requests to turn on Laravel PHP errors as part of our Server Management Services.
Today, let’s see how our Support Engineers use the debug feature to troubleshoot errors.
How to make Laravel show PHP errors
By default, the Laravel framework has an error handling feature. The debug option in the configuration file determines the error display at the user end.
Usually, the Laravel configuration file that enables debugging is the config/app.php. The debug option is set to default according to the APP_DEBUG variable in the .env file.
Basically, the .env file is a way to load custom configuration variables for Laravel. Hence, to make custom changes to Laravel, there is no need to modify web server files like .htaccess, virtual hosts and so on.
So, in the .env file, the APP_DEBUG variable is set to true to show PHP errors. This, in turn, changes the debug value in app.php to true. The debug option in app.php appear as,
Due to security reasons, showing errors all the time is also not recommended. Displaying Laravel PHP errors all the time in the browser will make the website vulnerable to website attacks.
Hence, our Support Team enables this feature only when we need to troubleshoot any error. After fixing the error, we turn off the debug feature.
Causes and fix for Laravel Debug not working
Sometimes, even after turning the debug value to true, Laravel does not show PHP errors. This is also a common request we often get from our customers. Let’s see how our Support Team fix this error.
1. Configuration setting in .env file
Some customers just change the debug value in config/app.php alone. This works fine in the production environment, but in the local environment, this does not display PHP errors.
So, our Support Team make sure that the following changes are made in .env file
APP_ENV=localAPP_DEBUG=true
When the configuration settings are proper then Laravel shows PHP errors in the browser. Due to security reasons, we always recommend our customers to turn on the debug feature only for troubleshooting.
2. Improper folder permissions
In some situations, the incorrect permissions of the storage and vendor directory in Laravel also causes the error. In this case, even the debug update in the .env file does not show PHP errors.
Usually, webserver needs write-access over Laravel folders storage and vendor.
For example, if the Apache web server is using a suPHP handler, then the PHP script runs with user permission. Thus the webserver will also have write permissions on the Laravel folders too.
But if the Apache webserver is running as a DSO module, then PHP application runs under nobody ownership. In this case, we need to give write permissions to the nobody user for using the Laravel folders.
Thus, our Support Engineers check the folder permissions and change it according to the web server in use.
3. The default setting in app.php
Occasionally, PHP files in the Laravel directory structure have some default settings that disable the debug feature.
For instance, the bootstrap directory contains an app.php file that loads the Laravel framework.
The app.php has some default settings, that comment some useful code related to debugging.
To fix this, we uncomment the line Dotenv::load(__DIR__.'/../');
in bootstrap/app.php to show PHP errors in Laravel.
Conclusion
So far, we saw how to make Laravel show PHP errors. We also discussed the possible errors that prevent error display in Laravel and how our Support Engineers fix them.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
- Configuration
- Handling Errors
- HTTP Exceptions
- Logging
Configuration
The logging facilities for your application are configured in the IlluminateFoundationBootstrapConfigureLogging
bootstrapper class. This class utilizes the log
configuration option from your config/app.php
configuration file.
By default, the logger is configured to use daily log files; however, you may customize this behavior as needed. Since Laravel uses the popular Monolog logging library, you can take advantage of the variety of handlers that Monolog offers.
For example, if you wish to use a single log file instead of daily files, you can make the following change to your config/app.php
configuration file:
'log' => 'single'
Out of the box, Laravel supported single
, daily
, syslog
and errorlog
logging modes. However, you are free to customize the logging for your application as you wish by overriding the ConfigureLogging
bootstrapper class.
Error Detail
The amount of error detail your application displays through the browser is controlled by the app.debug
configuration option in your config/app.php
configuration file. By default, this configuration option is set to respect the APP_DEBUG
environment variable, which is stored in your .env
file.
For local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
.
Handling Errors
All exceptions are handled by the AppExceptionsHandler
class. This class contains two methods: report
and render
.
The report
method is used to log exceptions or send them to an external service like BugSnag. By default, the report
method simply passes the exception to the base implementation on the parent class where the exception is logged. However, you are free to log exceptions however you wish. If you need to report different types of exceptions in different ways, you may use the PHP instanceof
comparison operator:
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param Exception $e
* @return void
*/
public function report(Exception $e)
{
if ($e instanceof CustomException)
{
//
}
return parent::report($e);
}
The render
method is responsible for converting the exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response.
The dontReport
property of the exception handler contains an array of exception types that will not be logged. By default, exceptions resulting from 404 errors are not written to your log files. You may add other exception types to this array as needed.
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a «page not found» error (404), an «unauthorized error» (401) or even a developer generated 500 error. In order to return such a response, use the following:
abort(404);
Optionally, you may provide a response:
abort(403, 'Unauthorized action.');
This method may be used at any time during the request’s lifecycle.
Custom 404 Error Page
To return a custom view for all 404 errors, create a resources/views/errors/404.blade.php
file. This view will be served on all 404 errors generated by your application.
Logging
The Laravel logging facilities provide a simple layer on top of the powerful Monolog library. By default, Laravel is configured to create daily log files for your application which are stored in the storage/logs
directory. You may write information to the log like so:
Log::info('This is some useful information.');
Log::warning('Something could be going wrong.');
Log::error('Something is really going wrong.');
The logger provides the seven logging levels defined in RFC 5424: debug, info, notice, warning, error, critical, and alert.
An array of contextual data may also be passed to the log methods:
Log::info('Log message', ['context' => 'Other helpful information']);
Monolog has a variety of additional handlers you may use for logging. If needed, you may access the underlying Monolog instance being used by Laravel:
$monolog = Log::getMonolog();
You may also register an event to catch all messages passed to the log:
Registering A Log Event Listener
Log::listen(function($level, $message, $context)
{
//
});
Laravel is a trademark of Taylor Otwell. Copyright © Taylor Otwell.
Design by Jack McDade
Edit by ngnam
- Introduction
- Configuration
- Обработчик исключений
- Reporting Exceptions
- Уровни журнала исключений
- Игнорирование исключений по типу
- Rendering Exceptions
- Отчетные и отображаемые исключения
- HTTP Exceptions
- Пользовательские страницы ошибок HTTP
Introduction
Когда вы начинаете новый проект Laravel, обработка ошибок и исключений уже настроена для вас. В классе AppExceptionsHandler
все исключения, создаваемые вашим приложением, регистрируются, а затем отображаются для пользователя. В этой документации мы углубимся в этот класс.
Configuration
Параметр debug
в config/app.php
конфигурации config / app.php определяет, сколько информации об ошибке фактически отображается пользователю. По умолчанию для этого параметра задано значение переменной среды APP_DEBUG
, которая хранится в вашем файле .env
.
Во время локальной разработки вы должны установить для переменной среды APP_DEBUG
значение true
. В производственной среде это значение всегда должно быть false
. Если в рабочей среде задано значение true
, вы рискуете раскрыть конфиденциальные значения конфигурации конечным пользователям вашего приложения.
Обработчик исключений
Reporting Exceptions
Все исключения обрабатываются классом AppExceptionsHandler
. Этот класс содержит метод register
, в котором вы можете зарегистрировать настраиваемые отчеты об исключениях и обратные вызовы рендеринга. Мы подробно рассмотрим каждое из этих понятий. Отчеты об исключениях используются для регистрации исключений или их отправки во внешние службы, такие как Flare , Bugsnag или Sentry . По умолчанию исключения будут регистрироваться в соответствии с вашей конфигурацией ведения журнала . Однако вы можете регистрировать исключения по своему усмотрению.
Например, если вам нужно по-разному сообщать об исключениях разных типов, вы можете использовать метод reportable
для регистрации замыкания, которое должно выполняться, когда необходимо сообщить об исключении данного типа. Laravel выведет, о каком типе исключения сообщает замыкание, изучив подсказку типа замыкания:
use AppExceptionsInvalidOrderException; public function register(){ $this->reportable(function (InvalidOrderException $e) {
При регистрации отчетов обратного вызова пользовательских исключений с использованием reportable
метода, Laravel будет по- прежнему регистрировать исключение , используя конфигурацию протоколирования по умолчанию для приложения. Если вы хотите остановить распространение исключения в стек журналов по умолчанию, вы можете использовать метод stop
при определении обратного вызова для отчетов или вернуть false
из обратного вызова:
$this->reportable(function (InvalidOrderException $e) { //})->stop(); $this->reportable(function (InvalidOrderException $e) { return false;});
Note
Чтобы настроить отчет об исключении для данного исключения, вы также можете использовать отчеты об исключениях .
Глобальный контекст журнала
Если доступно, Laravel автоматически добавляет идентификатор текущего пользователя в каждое сообщение журнала исключения в качестве контекстных данных. Вы можете определить свои собственные глобальные контекстные данные, переопределив метод context
класса AppExceptionsHandler
вашего приложения . Эта информация будет включена в каждое сообщение журнала исключения, написанное вашим приложением:
protected function context(){ return array_merge(parent::context(), [ 'foo' => 'bar', ]);}
Контекст журнала исключений
Хотя добавление контекста к каждому сообщению журнала может быть полезным, иногда конкретное исключение может иметь уникальный контекст, который вы хотели бы включить в свои журналы. Определив метод context
для одного из пользовательских исключений вашего приложения, вы можете указать любые данные, относящиеся к этому исключению, которые должны быть добавлены в запись журнала исключения:
<?php namespace AppExceptions; use Exception; class InvalidOrderException extends Exception{
report
Helper
Иногда вам может потребоваться сообщить об исключении, но продолжить обработку текущего запроса. Вспомогательная функция report
позволяет быстро сообщить об исключении через обработчик исключений, не отображая страницу ошибки для пользователя:
public function isValid($value){ try { // Validate the value... } catch (Throwable $e) { report($e); return false; }}
Уровни журнала исключений
Когда сообщения записываются в журналы вашего приложения , они записываются на указанном уровне журнала , который указывает серьезность или важность регистрируемого сообщения.
Как отмечалось выше, даже когда вы регистрируете настраиваемый обратный вызов для отчетов об исключениях с помощью метода reportable
, Laravel все равно будет регистрировать исключение, используя конфигурацию ведения журнала по умолчанию для приложения; однако, поскольку уровень журнала иногда может влиять на каналы, на которых регистрируется сообщение, вы можете настроить уровень журнала, на котором регистрируются определенные исключения.
Для этого вы можете определить массив типов исключений и связанных с ними уровней журналов в свойстве $levels
обработчика исключений вашего приложения:
use PDOException;use PsrLogLogLevel; protected $levels = [ PDOException::class => LogLevel::CRITICAL,];
Игнорирование исключений по типу
При создании вашего приложения будут некоторые типы исключений, которые вы просто захотите игнорировать и никогда не сообщать. Обработчик исключений вашего приложения содержит свойство $dontReport
, которое инициализируется пустым массивом. О любых классах, добавленных вами в это свойство, никогда не будет сообщено; однако они могут по-прежнему иметь пользовательскую логику рендеринга:
use AppExceptionsInvalidOrderException; protected $dontReport = [ InvalidOrderException::class,];
Note
За кулисами Laravel уже игнорирует некоторые типы ошибок, такие как исключения, возникающие из-за ошибок 404 HTTP «не найдено» или 419 ответов HTTP, сгенерированных недопустимыми токенами CSRF.
Rendering Exceptions
По умолчанию обработчик исключений Laravel преобразует исключения в HTTP-ответ. Однако вы можете зарегистрировать пользовательское закрытие рендеринга для исключений данного типа. Вы можете выполнить это с помощью метода renderable
вашего обработчика исключений.
Замыкание, переданное методу renderable
, должно возвращать экземпляр IlluminateHttpResponse
, который может быть сгенерирован с помощью помощника response
. Laravel определит, какой тип исключения вызывает замыкание, изучив подсказку типа замыкания:
use AppExceptionsInvalidOrderException; public function register(){ $this->renderable(function (InvalidOrderException $e, $request) { return response()->view('errors.invalid-order', [], 500); });}
Вы также можете использовать метод renderable
, чтобы переопределить поведение рендеринга для встроенных исключений Laravel или Symfony, таких как NotFoundHttpException
. Если закрытие, данное методу renderable
, не возвращает значение, будет использоваться рендеринг исключений Laravel по умолчанию:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException; public function register(){ $this->renderable(function (NotFoundHttpException $e, $request) { if ($request->is('api/*')) { return response()->json([ 'message' => 'Record not found.' ], 404); } });}
Отчетные и отображаемые исключения
register
обработчика исключений вы можете определить методы report
и render
непосредственно для ваших пользовательских исключений. Когда эти методы существуют, они будут автоматически вызываться фреймворком:
<?php namespace AppExceptions; use Exception; class InvalidOrderException extends Exception{ public function report() {
Если ваше исключение расширяет исключение, которое уже доступно для рендеринга, например, встроенное исключение Laravel или Symfony, вы можете вернуть false
из метода render
исключения , чтобы отобразить HTTP-ответ исключения по умолчанию:
public function render($request){
Если ваше исключение содержит настраиваемую логику отчетов, которая необходима только при выполнении определенных условий, вам может потребоваться указать Laravel иногда сообщать об исключении, используя конфигурацию обработки исключений по умолчанию. Для этого вы можете вернуть false
из метода report
об исключении :
public function report(){
Note
Вы можете указать любые требуемые зависимости методаreport
и они будут автоматически введены в метод контейнером служб Laravel .
HTTP Exceptions
Некоторые исключения описывают коды ошибок HTTP с сервера. Например, это может быть ошибка «страница не найдена» (404), «неавторизованная ошибка» (401) или даже ошибка 500, сгенерированная разработчиком. Чтобы сгенерировать такой ответ из любой точки вашего приложения, вы можете использовать помощник abort
:
abort(404);
Пользовательские страницы ошибок HTTP
Laravel упрощает отображение пользовательских страниц ошибок для различных кодов состояния HTTP. Например, если вы хотите настроить страницу ошибок для кодов состояния HTTP 404, создайте шаблон представления resources/views/errors/404.blade.php
. Это представление будет отображаться для всех ошибок 404, сгенерированных вашим приложением. Представления в этом каталоге должны быть названы в соответствии с кодом состояния HTTP, которому они соответствуют. Экземпляр SymfonyComponentHttpKernelExceptionHttpException
, вызванный функцией abort
, будет передан в представление как переменная $exception
:
<h2>{{ $exception->getMessage() }}</h2>
Вы можете опубликовать стандартные шаблоны страниц ошибок Laravel, используя Artisan-команду vendor:publish
. После публикации шаблонов вы можете настроить их по своему вкусу:
php artisan vendor:publish
Резервные страницы ошибок HTTP
Вы также можете определить «резервную» страницу ошибок для данной серии кодов состояния HTTP. Эта страница будет отображаться, если нет соответствующей страницы для определенного кода состояния HTTP, который произошел. Для этого определите шаблон 4xx.blade.php
и шаблон 5xx.blade.php
в каталоге resources/views/errors
вашего приложения .
Laravel
9.3
-
Encryption
-
Laravel Envoy
-
Events
-
Queued Event Listeners
Содержание
- Error Handling
- Introduction
- Configuration
- The Exception Handler
- Reporting Exceptions
- Global Log Context
- Exception Log Context
- The report Helper
- Exception Log Levels
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
- HTTP Exceptions
- Custom HTTP Error Pages
- Fallback HTTP Error Pages
- Laravel Framework Russian Community
- Введение
- Конфигурирование
- Обработчик исключений
- Отчет об исключениях
- Глобальное содержимое журнала
- Контекст журнала исключений
- Помощник report
- Игнорирование исключений по типу
- Отображение исключений
- Отчетные и отображаемые исключения
- HTTP-исключения
- Пользовательские страницы ошибок HTTP
Error Handling
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.
During local development, you should set the APP_DEBUG environment variable to true . In your production environment, this value should always be false . If the value is set to true in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler class. This class contains a register method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. However, you are free to log exceptions however you wish.
For example, if you need to report different types of exceptions in different ways, you may use the reportable method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
When you register a custom exception reporting callback using the reportable method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop method when defining your reporting callback or return false from the callback:
Note
To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context method of your application’s AppExceptionsHandler class. This information will be included in every exception’s log message written by your application:
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
The report Helper
Sometimes you may need to report an exception but continue handling the current request. The report helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
Exception Log Levels
When messages are written to your application’s logs, the messages are written at a specified log level, which indicates the severity or importance of the message being logged.
As noted above, even when you register a custom exception reporting callback using the reportable method, Laravel will still log the exception using the default logging configuration for the application; however, since the log level can sometimes influence the channels on which a message is logged, you may wish to configure the log level that certain exceptions are logged at.
To accomplish this, you may define an array of exception types and their associated log levels within the $levels property of your application’s exception handler:
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
Note
Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable method of your exception handler.
The closure passed to the renderable method should return an instance of IlluminateHttpResponse , which may be generated via the response helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
You may also use the renderable method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException . If the closure given to the renderable method does not return a value, Laravel’s default exception rendering will be utilized:
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register method, you may define report and render methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false from the exception’s render method to render the exception’s default HTTP response:
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false from the exception’s report method:
Note
You may type-hint any required dependencies of the report method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a «page not found» error (404), an «unauthorized error» (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort helper:
Custom HTTP Error Pages
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 view template. This view will be rendered 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 SymfonyComponentHttpKernelExceptionHttpException instance raised by the abort function will be passed to the view as an $exception variable:
You may publish Laravel’s default error page templates using the vendor:publish Artisan command. Once the templates have been published, you may customize them to your liking:
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php template and a 5xx.blade.php template in your application’s resources/views/errors directory.
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in most web projects.
Источник
Введение
Когда вы запускаете новый проект Laravel, обработка ошибок и исключений уже настроена для вас. Класс AppExceptionsHandler – это то место, где все исключения, созданные вашим приложением, регистрируются и затем отображаются пользователю. В этой документации мы углубимся в этот класс.
Конфигурирование
Параметр debug в конфигурационном файле config/app.php определяет, сколько информации об ошибке фактически отобразится пользователю. По умолчанию этот параметр установлен, чтобы учесть значение переменной окружения APP_DEBUG , которая содержится в вашем файле .env .
Во время локальной разработки вы должны установить для переменной окружения APP_DEBUG значение true . Во время эксплуатации приложения это значение всегда должно быть false . Если в рабочем окружении будет установлено значение true , вы рискуете раскрыть конфиденциальные значения конфигурации конечным пользователям вашего приложения.
Обработчик исключений
Отчет об исключениях
Все исключения обрабатываются классом AppExceptionsHandler . Этот класс содержит метод register , в котором вы можете зарегистрировать свои отчеты об исключениях и замыкания рендеринга. Мы подробно рассмотрим каждую из этих концепций. Отчеты об исключениях используются для регистрации исключений или отправки их во внешнюю службу, например Flare, Bugsnag или Sentry. По умолчанию исключения будут регистрироваться в соответствии с вашей конфигурацией логирования. Однако вы можете регистрировать исключения как хотите.
Например, если вам нужно сообщать о различных типах исключений по-разному, вы можете использовать метод reportable для регистрации замыкания, которое должно быть выполнено, когда необходимо сообщить об исключении конкретного типа. Laravel определит о каком типе исключения сообщает замыкание с помощью типизации аргументов:
Когда вы регистрируете собственные замыкания для создания отчетов об исключениях, используя метод reportable , Laravel по-прежнему регистрирует исключение, используя конфигурацию логирования по умолчанию для приложения. Если вы хотите остановить распространение исключения в стек журналов по умолчанию, вы можете использовать метод stop при определении замыкания отчета или вернуть false из замыкания:
Чтобы настроить отчет об исключениях для переданного исключения, вы можете рассмотреть возможность использования отчетных исключений.
Глобальное содержимое журнала
Если доступно, Laravel автоматически добавляет идентификатор текущего пользователя в каждое сообщение журнала исключения в качестве контекстных данных. Вы можете определить свои собственные глобальные контекстные данные, переопределив метод context класса AppExceptionsHandler вашего приложения. Эта информация будет включена в каждое сообщение журнала исключения, написанное вашим приложением:
Контекст журнала исключений
Хотя добавление контекста в каждое сообщение журнала может быть полезно, иногда конкретное исключение может иметь уникальный контекст, который вы хотели бы включить в свои журналы. Определив метод context для конкретного исключения вашего приложения, вы можете указать любые данные, относящиеся к этому исключению, которые должны быть добавлены в запись журнала исключения:
Помощник report
По желанию может потребоваться сообщить об исключении, но продолжить обработку текущего запроса. Помощник report позволяет вам быстро сообщить об исключении через обработчик исключений, не отображая страницу с ошибкой для пользователя:
Игнорирование исключений по типу
При создании приложения будут некоторые типы исключений, которые вы просто хотите игнорировать и никогда не сообщать о них. Обработчик исключений вашего приложения содержит свойство $dontReport , которое инициализируется пустым массивом. Ни о каких классах, добавленных в это свойство, никогда не будет сообщено; однако у них все еще может быть собственная логика отображения:
За кулисами Laravel уже игнорирует для вас некоторые типы ошибок, такие как исключения, возникающие из-за ошибок 404 HTTP «не найдено» или 419 HTTP-ответ, сгенерированный при недопустимом CSRF-токене.
Отображение исключений
По умолчанию обработчик исключений Laravel будет преобразовывать исключения в HTTP-ответ за вас. Однако вы можете зарегистрировать свое замыкание для отображения исключений конкретного типа. Вы можете сделать это с помощью метода renderable обработчика исключений.
Замыкание, переданное методу renderable , должно вернуть экземпляр IlluminateHttpResponse , который может быть сгенерирован с помощью функции response . Laravel определит, какой тип исключения отображает замыкание с помощью типизации аргументов:
Вы также можете использовать метод renderable чтобы переопределить отображение для встроенных исключений Laravel или Symfony, таких, как NotFoundHttpException . Если замыкание, переданное методу renderable не возвращает значения, будет использоваться отрисовка исключений Laravel по умолчанию:
Отчетные и отображаемые исключения
Вместо проверки типов исключений в методе register обработчика исключений вы можете определить методы report и render непосредственно для ваших исключений. Если эти методы существуют, то они будут автоматически вызываться фреймворком:
Если ваше исключение расширяет исключение, которое уже доступно для визуализации, например встроенное исключение Laravel или Symfony, вы можете вернуть false из метода render исключения, чтобы отобразить HTTP-ответ исключения по умолчанию:
Если ваше исключение содержит пользовательскую логику отчетности, которая необходима только при выполнении определенных условий, то вам может потребоваться указать Laravel когда сообщать об исключении, используя конфигурацию обработки исключений по умолчанию. Для этого вы можете вернуть false из метода report исключения:
Вы можете указать любые требуемые зависимости метода report , и они будут автоматически внедрены в метод контейнером служб Laravel.
HTTP-исключения
Некоторые исключения описывают коды HTTP-ошибок с сервера. Например, это может быть ошибка «страница не найдена» (404), «неавторизованный доступ» (401) или даже ошибка 500, сгенерированная разработчиком. Чтобы создать такой ответ из любой точки вашего приложения, вы можете использовать глобальный помощник abort :
Пользовательские страницы ошибок HTTP
Laravel позволяет легко отображать пользовательские страницы ошибок для различных кодов состояния HTTP. Например, если вы хотите настроить страницу ошибок для кодов HTTP-состояния 404, создайте файл resources/views/errors/404.blade.php . Это представление будет отображено для всех ошибок 404, сгенерированных вашим приложением. Шаблоны в этом каталоге должны быть названы в соответствии с кодом состояния HTTP, которому они соответствуют. Экземпляр SymfonyComponentHttpKernelExceptionHttpException , вызванный функцией abort , будет передан в шаблон как переменная $exception :
Вы можете опубликовать стандартные шаблоны страниц ошибок Laravel с помощью команды vendor:publish Artisan. После публикации шаблонов вы можете настроить их по своему вкусу:
Источник