Catch swiftmailer exception in Symfony2 dev env controller - symfony

Im not sure why Im not catching exceptions from Swiftmailer in my controller. What am I doing wrong, or missing?
In a controller I have:
try {
$this->get('mailer')->send($email);
}
catch (\Swift_TransportException $e) {
$result = array(
false,
'There was a problem sending email: ' . $e->getMessage()
);
}
It seems to get caught by Symfony before it gets to my code, so instead of being able to handle the error myself I get the standard 500 page with
Swift_TransportException: Connection could not be established
If the email can't be sent there is no need for the application to halt as the email isn't critical - I just want to issue a notice.
Maybe there's a way to disable Symfonys catching of certain exceptions or for certain Controllers?

When you do $this->container->get("mailer")->send($email); the email message is not being sent at that point if you have spooling turned on. See http://symfony.com/doc/current/cookbook/email/spool.html
If you have the default setting of spool: { type: memory }, the \Swift_TransportException will be thrown during the kernel termination phase, after your controller has exited.
One way around this is to turn off the spooling (but then your users might have to wait while the email is sent), or you can make your own eventlistener to handle the exception. http://symfony.com/doc/current/cookbook/service_container/event_listener.html

You can try overriding the Twig Exception Handler in config.yml:
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
exception_controller: MyBundleName:Exception:show
You then create an Exception class which extends:
Symfony\Bundle\TwigBundle\Controller\ExceptionController
Read the source code of that file and then override the methods to switch which template is rendered when the Exception type is Swift_TransportException
You can do that by setting a class variable in showAction() and passing it to findTemplate()
showAction:
$this->exceptionClassName = $exception->getClass();
findTemplate:
if (!$debug && $this->exceptionClassName == 'MyBundle\Exception\GenericNotFoundException') {
return 'BundleName:Exception:generic404.html.twig';
}
For more information, I recommend the KNPUniversity Symfony Screencasts.

Related

Monolog handler ignoring yaml level

In Symfony 4.3 using Monolog, I have created a custom handler to push logs to AWS Firehose. Here is the constructor:
class FirehoseLogHandler extends AbstractProcessingHandler {
public function __construct(
FirehoseClient $firehoseClient,
FormatterInterface $formatter,
$streamName,
$level = Logger::INFO,
$bubble = true
) {
$this->firehoseClient = $firehoseClient;
$this->streamName = $streamName;
$this->formatter = $formatter;
parent::__construct($level, $bubble);
}
And here is my monolog.yaml config:
monolog:
handlers:
firehose_handler:
type: service
id: kinesis_stream_handler
main:
type: stream
handler: firehose_handler
level: error
channels: ["!event"]
services:
kinesis_stream_handler:
class: App\Logger\Handler\FirehoseLogHandler
arguments:
$firehoseClient: '#aws.firehose'
$formatter: '#App\Logger\Formatter\FirehoseLogFormatter'
$streamName: 'firehose-stream-test'
The problem that I am having is that the $level is always set to Logger::INFO (200), or whatever is set in the constructor. It seems to be ignoring what is set in the yaml config.
What am I doing wrong here? I know I could always add $level: 400 to the service declaration but that doesn't seem to make much sense. Appreciate any help in advance.
Handlers defined as type: service are used strictly as-is, since they are instances you have already constructed. They are not passed any arguments from the main monolog configuration; that would only apply to services it is constructing for you. So you do need to add $level as an explicit argument to your custom handler for this reason.
There may be some further confusion stemming from your main handler definition. While handler is a valid configuration key, it does not apply to a stream handler as it only makes sense for handlers that wrap others, such as filter. So that is simply being ignored.
The full list of handler types and what configuration keys actually apply to each can be found in the code here.

Throwing Exception in an EventSubscriber prevent ApiPlatform from serializing it so i only get standard symfony error page

i'm trying to do some process in an EventSubscriber listening to the request. To make it simple i want to check a header and refuse the request if i don't find it. It's almost like a Guard, but quite simpler.
In that step i might throw an Exception. And it works, except that i would like apiPlatform to manage the response and serialize it.
I have already configure ApiPlatform with packages/api_platform.yaml
api_platform:
exception_to_status:
Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException: 403
My EventSubscriber is configured like this in services.yaml
services:
app.security.api_subscriber:
class: App\Security\ApiAccessSubscriber
arguments:
- "%api.authorized.keys%"
calls:
- [setClient, ["#common-sentry-api"]]
- [setClientPerUser, ["#common-sentry-peruser"]]
My Subscriber describe itself like this:
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onKernelRequest', EventPriorities::POST_WRITE],
];
}
What am i doing wrong ?

Symfony3 404 exception response return with status code 200 instead of 500

I am new in symfony,I have facing one problem in Production Environment after I add kernel.event_subscriber in service.yml. problem is before adding event subscriber in service.yml file It return 500 HTTP_STATUS_CODE & Resource Not Found exception occur with my custom page in twingbuddle That I set, below page it show before add event_subscriber In Service.yml When I go to URL: http://localhost/meopin_2/trunk/web/en/login/ddssssssssss,
Then I add below code in Service.yml
kernel.event_subscriber:
class: AppBundle\EventSubscriber\TokenSubscriber
arguments: ["#security.http_utils","#service_container","#router", {}, {}, {},{}]
tags:
- { name: kernel.event_subscriber, channel: 'kernel' ,event: onKernelController,method: onKernelController}
and make a File Event Describer. Now issue is When I go to Same URL: http://localhost/meopin_2/trunk/web/en/login/ddssssssssss
It Return me Error as a Text Message with HTTP_STATUS_CODE 200, Below response It Return Me Instead of My Previous 404 Page in Production Environment.
What I missing or Wrong So that It return error as a text message in Production Environment ?
Thanks In Advance if Any one help me.

Symfony 2.8 disable security/request.INFO logging

Symfony is logging two INFO level statements for every request in my application, inflating an apache log file very rapidly. We're not using Monolog (using an alternate solution), and I've disabled it by removing the bundle in the AppKernel.
[2016-06-23 12:11:04] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2016-06-23 12:11:06] request.INFO: Matched route "contact". {"route_parameters":{"_controller": ...
How can I disable this logging?
This happens because Monolog (which symfony will use itself even if you disable it in your app) defaults to std:error:
public function addRecord($level, $message, array $context = array())
{
if (!$this->handlers) {
$this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
}
Adding any handler in app/config/config.yml will make addRecord reject the unwanted info notice instead.
monolog:
handlers:
syslog:
type: syslog
level: error

Symfony - using twig trans filter on 404 page

I have a 404 error page set up through an event listener triggered by Kernel exceptions:
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($event->isMasterRequest()) {
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
$response = new Response();
$event->setResponse(
$response->setContent($this->templating->render(
'LandingPageBundle:Error:error404.html.twig',
['welcome_url' => $this->router->generate("welcome")]
))
);
}
}
}
kernel.kernel_exception_listener:
class: S\Project\LandingPageBundle\EventListener\KernelExceptionListener
arguments: [ "#router", "#logger", "#translator", #templating ]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
This works, but when I try to use the trans filter on the twig error404.html.twig template, it does nothing. My locale is being set in a cookie and read by an event listener to Kernel Requests, so I tried adding the following to onKernelException:
$request = $event->getRequest();
$locale = $request->cookies->get('_locale');
$request->setLocale($locale);
After that, including {{ app.request.locale }} in the template displayed the correct locale, however, the trans filter does not seem to be picking this up.
It seems like my problem may be related to Symfony 2.1 set locale and yet that question does not quite fit my exact problem, and I'm not sure what can be done to fix the problem. Ideally my kernel request listener could trigger before the onKernelException, so that it would properly set the locale beforehand, but currently it seems that the kernel request event is not triggered during a 404. I took a look at http://symfony.com/doc/current/components/http_kernel/introduction.html to better understand Symfony's request sequence, but I'm not really clear on the sequence that happens in a bad request, but it looks like in the case of an exception, it skips most of the request flow and goes straight to the response, and as I recall from http://symfony.com/doc/current/book/translation.html#handling-the-user-s-locale
"Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service."
Is there a way to use the trans filter on a twig templated 404 page?
Try to inject the #translator and use its method setLocale.
['welcome_url' => $this->router->generate("welcome")]
And why did you create link in the listener? You should do it in the template using twig function called path.

Resources