CodelyTV / php-ddd-example

🐘🎯 Hexagonal Architecture + DDD + CQRS in PHP using Symfony 7
https://pro.codely.tv/library/ddd-en-php
2.98k stars 1.08k forks source link

Undefined method getException() on RequestEvent class #147

Closed mb3rnard closed 4 years ago

mb3rnard commented 4 years ago

I came across this error while trying to access http://api.codelytv.localhost:8030/

Attempted to call an undefined method named "getException" of class "Symfony\Component\HttpKernel\Event\ExceptionEvent".

To make it work, I changed a few things in this class:

which results in the following:

final class ApiExceptionListener
{
    private ApiExceptionsHttpStatusCodeMapping $exceptionHandler;

    public function __construct(ApiExceptionsHttpStatusCodeMapping $exceptionHandler)
    {
        $this->exceptionHandler = $exceptionHandler;
    }

    public function onException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();

        $event->setResponse(
            new JsonResponse(
                [
                    'code'    => $this->exceptionCodeFor($exception),
                    'message' => $exception->getMessage(),
                ],
                $this->exceptionHandler->statusCodeFor(get_class($exception))
            )
        );
    }

    private function exceptionCodeFor(\Throwable $error): string
    {
        $domainErrorClass = DomainError::class;

        return $error instanceof $domainErrorClass ? $error->errorCode() : Utils::toSnakeCase(get_class($error));
    }
}

These are not optimal changes by any means, but they allowed me to display a fully functionnal error message on the homepage.

rgomezcasas commented 4 years ago

Thanks to https://github.com/CodelyTV/php-ddd-example/pull/163 this should be fixed now! :)