Skip to content

[DependencyInjection] ContainerInterface::get and Container::get throws tag are not consistent #51834

Closed
@VincentLanglet

Description

@VincentLanglet

Symfony version(s) affected

5.4.x

Description

ContainerInterface::get throws tags are
https://github.com/symfony/symfony/blob/6.4/src/Symfony/Component/DependencyInjection/ContainerInterface.php

* @throws ServiceCircularReferenceException When a circular reference is detected
* @throws ServiceNotFoundException          When the service is not defined

Which means I should be able to write code

public function do(ContainerInterface $c) {
     try {
         $c->get(...);
    } catch (ServiceCircularReferenceException|ServiceNotFoundException) {
        return;
    }
}

with no exception thrown.

But seems like one implementation Container can throw any exception, cf
https://github.com/symfony/symfony/blob/6.4/src/Symfony/Component/DependencyInjection/Container.php#L204
So it doesn't respect the interface.

How to reproduce

Irrelevant

Possible Solution

Either \Exception should be removed from Container or added to the interface.

But even \Exception should be improved:

  • An interface CustomExceptionInterface or Throwable should be preferred
  • If it's an exception thrown by Symfony it should be Symfony-scoped like every others Symfony\Foo\Exception
  • If it's an exception thrown by the User it should be Throwable

I think the \Exception is coming from here,
https://github.com/symfony/symfony/blob/6.4/src/Symfony/Component/DependencyInjection/Container.php#L237

A nice solution could be to:

  • Introduce a ServiceLoadingException implements Symfony\Component\DependencyInjection\Exception\ExceptionInterface
  • re-throw new ServiceLoadingException('...', $e->getCode(), $e); instead of $e directly.
  • Updating the ContainerInterface to add @throws ServiceLoadingException

WDYT ? This would be done with #51835

Additional Context

This was added here: 1775da5#diff-98156f7ccbe7f78db5bc7ff3f81ddb5a76532f652dd7520f38b472219d92f394R264 by @xabbuh

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions