Skip to content

Commit

Permalink
make errors more consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
esler committed Jun 6, 2019
1 parent ba7371b commit fff783f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
44 changes: 35 additions & 9 deletions src/ServiceContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,16 +174,8 @@ public function make(string $id)
if (null === $instance) {
throw new EmptyResultFromFactoryException($id);
}
} catch (NotFoundExceptionInterface|ContainerExceptionInterface $exception) {
throw $exception;
} catch (\ReflectionException $exception) {
throw new ReflectionError($exception);
} catch (\Throwable $error) {
if (sprintf("Class '%s' not found", $id) === $error->getMessage()) {
throw new ServiceNotFoundException($id, $error);
} else {
throw new CannotMakeServiceException($id, $error);
}
$this->handleError($id, $error);
}

return $instance;
Expand Down Expand Up @@ -269,6 +261,40 @@ public function unset(string $id): bool {
return false;
}

/**
* Handles an error when making a service
*
* @param string $id ID of entry we're creating
* @param \Throwable $error en error
*
* @return void
*/
private function handleError(string $id, \Throwable $error): void {
if ($error instanceof NotFoundExceptionInterface) {
throw $error;
}

if ($error instanceof ContainerExceptionInterface) {
throw $error;
}

if ($error instanceof \ReflectionException) {
throw new ReflectionError($error);
}

if (\sprintf("Class '%s' not found", $id) === $error->getMessage()) {
throw new ServiceNotFoundException($id, $error);
}

if (!$this->autowireEnabled) {
if ($error instanceof \ArgumentCountError) {
throw new CannotMakeServiceException($id, $error);
}
}

throw $error;
}

private static function buildFactory($classname)
{
try {
Expand Down
6 changes: 3 additions & 3 deletions tests/ServiceContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ function testGettingNonExistingClass(string $id) {
$container->get($id);
}

function testGettingClassWithConstructorError() {
function testThatExceptionNotRelatedWithServiceMakingAreDisclosed() {
$container = new ServiceContainer;

$this->expectException(CannotMakeServiceException::class);
$this->expectExceptionMessage('Cannot make service, id: ClassWithFalseConstructor');
$this->expectException('Exception');
$this->expectExceptionMessage('blah blah');
$container->get(ClassWithFalseConstructor::class);
}

Expand Down

0 comments on commit fff783f

Please sign in to comment.