Как настроить страницы ошибок¶
В приложениях Symfony все ошибки воспринимаются, как исключения, вне зависимости от того, являются ли они простой ошибкой 404 “Не найдено” или фатальной ошибкой, запущенной вызовом какого-то исключения в вашем коде.
Так как эти страницы содержат много чувствительной внутренней информации, Symfony не будет отображать её в окружении производства. Вместо этого, она покажет простую и общую ошибку страница ошибки:
Страницы ошибок в окружении производства можно настроить разными способами, в зависимости от ваших потребностей:
Переопределение шаблонов ошибок по умолчанию¶
Вы можете использовать встроенное средство отображения ошибок Twig, чтобы переопределять шаблоны ошибок по умолчанию. Для этого должны быть установлены как TwigBundle, так и TwigBridge. Выполните эту команду, чтобы убедиться, что они оба установлены:
Этот контроллер использует статус-код HTTP, формат запроса и следующую логику, чтобы определить имя файла шаблона:
Типичный проект, возвращающий страницы HTML и JSON, может выглядеть так:
Пример шаблона ошибки 404¶
Безопасность и страницы 404¶
В связи с порядком, в котором загружаются маршрутизация и безопасность, конфиденциальна информация не будет доступна на ваших страницах 404. Это означает, что будет казаться, что ваш пользователь не залогинен в систему на странице 404 (это будет работать при тестировании, но не в производстве).
Тестирование страниц ошибок по время разработки¶
В то время, как вы находитесь в окружении разработки, Symfony отображает большую страницу исключений вместо вашей новой блестящей страницы ошибок. Так как вам увидеть, как она выглядит изнутри и отладить её?
К счастью, ExceptionController по умолчанию разрешает вам предпросмотр вашей страницы ошибки во время разработки.
Как настроить страницы ошибок¶
В приложениях Symfony все ошибки воспринимаются, как исключения, вне зависимости от того, являются ли они простой ошибкой 404 “Не найдено” или фатальной ошибкой, запущенной вызовом какого-то исключения в вашем коде.
Так как эти страницы содержат много чувствительной внутренней информации, Symfony не будет отображать её в окружении производства. Вместо этого, она покажет простую и общую ошибку страница ошибки:
Страницы ошибок в окружении производства можно настроить разными способами, в зависимости от ваших потребностей:
Переопределение шаблонов ошибок по умолчанию¶
Вы можете использовать встроенное средство отображения ошибок Twig, чтобы переопределять шаблоны ошибок по умолчанию. Для этого должны быть установлены как TwigBundle, так и TwigBridge. Выполните эту команду, чтобы убедиться, что они оба установлены:
Этот контроллер использует статус-код HTTP, формат запроса и следующую логику, чтобы определить имя файла шаблона:
Типичный проект, возвращающий страницы HTML и JSON, может выглядеть так:
Пример шаблона ошибки 404¶
Безопасность и страницы 404¶
В связи с порядком, в котором загружаются маршрутизация и безопасность, конфиденциальна информация не будет доступна на ваших страницах 404. Это означает, что будет казаться, что ваш пользователь не залогинен в систему на странице 404 (это будет работать при тестировании, но не в производстве).
Тестирование страниц ошибок по время разработки¶
В то время, как вы находитесь в окружении разработки, Symfony отображает большую страницу исключений вместо вашей новой блестящей страницы ошибок. Так как вам увидеть, как она выглядит изнутри и отладить её?
К счастью, ExceptionController по умолчанию разрешает вам предпросмотр вашей страницы ошибки во время разработки.
A guide to custom error handling in Symfony
When working on a Symfony project some time ago, our team faced an issue with handling exceptions. An internal API needed to react to some explicit exceptions in a way that differs from the normal approach. So what did we do?
Thanks to the TwigBundle and to the _format: json parameter in the routing, the typical error response in the production environment looked like the below:
We wanted to keep this functionality across the system, but for some explicit exceptions, we wanted something more descriptive, like:
One approach was to use a configuration from FOSRestBundle, passing custom exception codes and messages in the fos_rest configuration.
But the solution came with a couple disadvantages:
We also didn’t want to rely on a TwigBundle changing the way its ExceptionController handles exceptions. Nor did we want to throw HttpExceptions in the domain model code as HTTP is just the one of the adapters for the application.
The best and very clean solution here was to write our own event listener dispatched on the Symfony KernelException event. As this may be quite a common use case, here is a tutorial on how to write your custom exception listener in a Symfony-based application.
Solution
First, we need a Symfony application. For the demo purposes, I’ve created a repository here: https://github.com/mheki/ExceptionListenerDemo.
This simple application comes with the GreeterController, which is registered as a service. I personally prefer this approach to introduce more visibility for my controller’s dependencies. But there is no problem with extending Symfony base controller if one prefers that way. More information about how to define controllers as services can be found in the official Symfony documentation.
and a simple greeter service which has the responsibility of greeting people except thieves:
If you try to greet a thief, you get a standard HTML exception message which is a bit messy.
Let’s try to fix it with the event listener.
First of all, we want to identify a contract of exceptions with the error messages published to the response.
Let’s create a PublishedMessageException Interface:
Let’s keep it as simple as possible:
The last thing left is to register our listener as a service with the correct tag:
To check if the demo works, let’s run the built-in server: bin/console server:run
Now sending a GET request: curl http://localhost:8000/greet/Marek will return a response:
Conclusion
This simple tutorial shows how useful, powerful and convenient Symfony event listeners are. They allow you to delegate some additional functionality, which can also be easily disabled if the requirements change.
Read more about event listeners in the official Symfony cookbook and the Event Dispatcher component documentation.
Handling and logging exceptions in Symfony API applications
We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.
In this example we are going to catch all our custom exceptions and log them in a log file. Apart from that, we will return an appropriate HTTP status code and text message to the user.
When developing an API application, catch all exceptions and throw your custom ones. This way, you have full control over «proper» exception handling as shown in this example. The whole point here is that, returning sensible responses to the end user, not accidental 500 codes!
monolog.yaml
Add channels: [‘api’] entry to all «monolog.yaml» files so that our custom errors can be logged in «test».log», «dev».log» and «prod».log» files. Or, just create a custom handler to log them in custom log file instead.
ApiExceptionInterface
All your custom exceptions should implement this.
CountryException
All your custom exceptions should be same as this.
ExceptionListener
If your API returns request validation errors as in JSON form, you can modify the response message below to meet your needs, such as returning a JSON response instead.
New in Symfony 4.1: Exception improvements
FlattenException now unwraps errors¶
In Symfony 4.1, FlattenException now unwraps FatalThrowableError instances and logs the wrapped error. In consequence, the real error class is now always displayed in the exception page:
Introduced new exception classes¶
In Symfony 4.1 we’ve introduced a new ProcessSignaledException class in the Process component to properly catch signaled process errors. Also, in the HttpFoundation component, we’ve introduced new detailed exception classes for file upload handling to replace the generic catch-all FileException :
Moreover, now that PHP 7.1 supports multi catch exception handling, you can process several exceptions with the same catch() block:
Improved the exception page design¶
The exception pages have been improved in Symfony 4.1 to display less information about «vendor code». If some code belongs to the vendor/ folder, we compact its information to fit in a single line and we no longer display its arguments. The other code remains the same, which helps you focus more easily on your own application code:
Comments
Become a certified developer! Exams are online and available in all countries.
Julien Manganne Certified said on Apr 24, 2018 at 11:31 #1
Lynn van der Berg said on Apr 24, 2018 at 11:50 #2
Jovan Perovic said on Apr 24, 2018 at 11:52 #3
Bastien Gatellier said on Apr 24, 2018 at 13:12 #4
Guillaume Loulier Certified said on Apr 24, 2018 at 18:52 #5
Geoffrey Maddock said on Apr 24, 2018 at 20:19 #6
Hamza Amrouche said on Apr 25, 2018 at 08:01 #7
Stéphane BOURSE said on Apr 25, 2018 at 17:11 #8
Alex Barylski said on Apr 29, 2018 at 02:27 #9
Lýdia Hiľovská said on Jun 9, 2018 at 14:48 #10
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Latest from the Symfony Blog
They Help Us Make Symfony
Get Involved in the Community
A passionate group of over 600,000 developers from more than 120 countries, all committed to helping PHP surpass the impossible.
Symfony™ is a trademark of Symfony SAS. All rights reserved.
















