Reputation: 1655
I am trying to understand how to build a event Listener in Symfony and how it works.
so I have looked at the Example calss from Symfony Docs.
<?php
// src/AppBundle/EventListener/AcmeExceptionListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class AcmeExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
$message = sprintf(
'My Error says: %s with code: %s',
$exception->getMessage(),
$exception->getCode()
);
// Customize your response object to display the exception details
$response = new Response();
$response->setContent($message);
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Send the modified response object to the event
$event->setResponse($response);
}
}
I understand that $event->getException()
from GetResponseForExceptionEvent class picks a Event throwns in my application
What i don't quiet understand is how does why $exception
can use getMessage()
and getCode()
.
Can someone briefly explain these to me and Maybe a bit more about Symfony Event Listener.
Upvotes: 2
Views: 553
Reputation: 3356
This is a huge topic and I found it hard to understand when I was learning it via Symfony documentation and other online blogs. I will recommend you to view this tutorial from KNP University and believe me you will have a very clear understanding of it.
Upvotes: 4
Reputation: 4116
That has nothing to do with Symfony Events, when yo use $event->getException
you are getting an instance of class Exception, this class has those methods defined.
Upvotes: 1
Reputation: 810
The last question first.
why
$exception
can usegetMessage()
andgetCode()
Symfony is a framework that use strict Objcet Oriented paradigm. So oftenly a function:
In this example for simplicity we can think, $exception
is an Exception
object that have properties that can be see in here.
Also to understands how listeners works, it help if you have some knowledge about "Observer Design Pattern". This is a litle explanation.
And to understanding your code, you create a listeners that active when Exception
is thrown from anywhere. So you can choose to or not to show your error message.
Upvotes: 0