Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

php - Symfony: Best place to catch exception (CQRS/DDD)

I've a personal application. I use design pattern CQRS/DDD for a API.

Schema: User --> Controller (dispatch command) --> Command handler --> some services...

In my Rest API controller

$this->dispatch($cmd);

If a throw a exception in services or specification classes for example, ok, I've a listener to catch exception and create JSON response error.

But if I want to develop an interface module with TWIG, I think I will not use my listener because I don't want a JSON response.

Should I used try/catch in my controller of my new interface module ?

SomeController extends AbstractController
{
    public function getObject($id)
    {
         try {
            $this->dispatch($cmd);
        catch(SomeException $ex) {
            $this->render(....)
        } 
    }
}

Where is the best place to catch exception for TWIG ?

Thanks.

Edit:

@Cid if (some conditions && $form->handleRequest($request)->isValid()) --> My handler don't return bool or values.

Imagine this code. Imagine I want share a service between an API and web view app.

class ApiController
{
    public function register()
    {
        $this->dispatch($cmd);
    }
}

class WebController
{
    public function register()
    {
        $this->dispatch($cmd);
    }
}

class SomeHandler implements CommandHandlerInterface
{

    /** @required */
    public RegisterService $service;

    public function __invoke(SomeCommand $command)
    {
        $this->service->register($command->getEmail())
    }
}

class RegisterService
{
    public function register(string $email)
    {
        // Exception here
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So, I think the best place to handle Exception is EventSubscriber, see here: https://symfony.com/doc/current/reference/events.html#kernel-exception

use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpKernelEventExceptionEvent;

public function onKernelException(ExceptionEvent $event)
{
    $exception = $event->getThrowable();
    $response = new Response();
    // setup the Response object based on the caught exception
    $event->setResponse($response);

    // you can alternatively set a new Exception
    // $exception = new Exception('Some special exception');
    // $event->setThrowable($exception);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...