Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle all uncaught Exceptions and rejected promises with error page with status 500 (Internal Server Error) #12

Merged
merged 3 commits into from
Mar 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"Frugal\\": "src/"
}
},
"require": {
"php": ">=7.1",
"nikic/fast-route": "^1.3",
Expand All @@ -23,5 +18,15 @@
},
"require-dev": {
"phpunit/phpunit": "^9.5 || ^7.5"
},
"autoload": {
"psr-4": {
"Frugal\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Frugal\\Tests\\": "tests/"
}
}
}
7 changes: 7 additions & 0 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,5 +129,12 @@
);
});

$app->get('/error', function () {
throw new RuntimeException('Error');
});
$app->get('/error/null', function () {
return null;
});

$app->run();
$loop->run();
82 changes: 80 additions & 2 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,11 @@ private function sendResponse(ServerRequestInterface $request, ResponseInterface
/**
* @param ServerRequestInterface $request
* @param Dispatcher $dispatcher
* @return ResponseInterface|PromiseInterface<ResponseInterface>
* @return ResponseInterface|PromiseInterface<ResponseInterface,void>
* Returns a response or a Promise which eventually fulfills with a
* response. This method never throws or resolves a rejected promise.
* If the request can not be routed or the handler fails, it will be
* turned into a valid error response before returning.
*/
private function handleRequest(ServerRequestInterface $request, Dispatcher $dispatcher)
{
Expand All @@ -326,7 +330,30 @@ private function handleRequest(ServerRequestInterface $request, Dispatcher $disp
$request = $request->withAttribute($key, rawurldecode($value));
}

return $handler($request);
try {
$response = $handler($request);
} catch (\Throwable $e) {
return $this->errorHandlerException($e, $handler);
}

if ($response instanceof ResponseInterface) {
return $response;
} elseif ($response instanceof PromiseInterface) {
return $response->then(function ($response) use ($handler) {
if (!$response instanceof ResponseInterface) {
return $this->errorHandlerResponse($response, $handler);
}
return $response;
}, function ($e) use ($handler) {
if ($e instanceof \Throwable) {
return $this->errorHandlerException($e, $handler);
} else {
return $this->errorHandlerResponse(\React\Promise\reject($e), $handler);
}
});
} else {
return $this->errorHandlerResponse($response, $handler);
}
}
} // @codeCoverageIgnore

Expand Down Expand Up @@ -403,4 +430,55 @@ private function errorMethodNotAllowed(ServerRequestInterface $request): Respons
implode(', ', $request->getAttribute('allowed'))
)->withHeader('Allowed', implode(', ', $request->getAttribute('allowed')));
}

private function errorHandlerException(\Throwable $e, callable $handler): ResponseInterface
{
$where = ' (<code title="See ' . $e->getFile() . ' line ' . $e->getLine() . '">' . \basename($e->getFile()) . ':' . $e->getLine() . '</code>)';

return $this->error(
500,
'Uncaught <code>' . \get_class($e) . '</code> from ' . \lcfirst($this->describeHandler($handler, false)) . $where . ': ' . $e->getMessage()
);
}

private function errorHandlerResponse($value, callable $handler): ResponseInterface
{
return $this->error(
500,
$this->describeHandler($handler, true) . ' returned invalid value (<code>' . $this->describeType($value) . '</code>)'
);
}

private function describeType($value): string
{
if ($value === null) {
return 'null';
} elseif (\is_scalar($value) && !\is_string($value)) {
return \var_export($value, true);
}
return \is_object($value) ? \get_class($value) : \gettype($value);
}

private function describeHandler(callable $handler, bool $linkSourceFile): string
{
if (\is_object($handler) && !$handler instanceof \Closure) {
$ref = new \ReflectionMethod($handler, '__invoke');
$name = '<code>' . \get_class($handler) . '</code>';
} elseif (\is_string($handler)) {
$ref = new \ReflectionFunction($handler);
$name = '<code>' . $handler . '()</code>';
} elseif (\is_array($handler)) {
$ref = new \ReflectionMethod($handler[0], $handler[1]);
$name = '<code>' . (\is_string($handler[0]) ? $handler[0] : \get_class($handler[0])) . '::' . $handler[1] . '()</code>';
} else {
$ref = new \ReflectionFunction($handler);
$name = 'Request handler';
}

if ($linkSourceFile && !$ref->isInternal()) {
$name .= ' (<code title="See ' . $ref->getFileName() .' line ' . $ref->getStartLine() .'">' . \basename($ref->getFileName()) . ':' . $ref->getStartLine() . '</code>)';
}

return $name;
}
}
Loading