-
-
Notifications
You must be signed in to change notification settings - Fork 139
feat(router): support giving back json when a request fail #1629
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
Closed
NeoIsRecursive
wants to merge
16
commits into
tempestphp:main
from
NeoIsRecursive:feat/json-exception-responses
+257
−103
Closed
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
51dac55
wip
NeoIsRecursive 78ab00d
wip
NeoIsRecursive 43fae97
wip
NeoIsRecursive 756e8c5
fix if statement...
NeoIsRecursive 29d4e50
feat: add `JsonHttpExceptionHandler`
NeoIsRecursive 297bbd2
wip prettify validation error responses
NeoIsRecursive cd71ee1
wip
NeoIsRecursive a606488
Merge remote-tracking branch 'upstream/main' into feat/json-exception…
NeoIsRecursive 2eb3c9f
use accepts method
NeoIsRecursive 3b9afa4
wip
NeoIsRecursive 146337d
wip remove unnesxtwcgwy dependecies in jsonException renderer
NeoIsRecursive 9ae3c24
wip
NeoIsRecursive 61db1f0
Merge branch 'main' into feat/json-exception-responses
brendt c8a0cd1
Merge branch 'main' into feat/json-exception-responses
brendt bf05f0d
wip
NeoIsRecursive 0c5418d
add test that doesnt work
NeoIsRecursive File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\Http\Responses; | ||
|
|
||
| use Tempest\Http\IsResponse; | ||
| use Tempest\Http\Response; | ||
| use Tempest\Http\Status; | ||
|
|
||
| final class NotAcceptable implements Response | ||
| { | ||
| use IsResponse; | ||
|
|
||
| public function __construct() | ||
| { | ||
| $this->status = Status::NOT_ACCEPTABLE; | ||
| } | ||
| } |
119 changes: 119 additions & 0 deletions
119
packages/router/src/Exceptions/HtmlExceptionRenderer.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| <?php | ||
|
|
||
| namespace Tempest\Router\Exceptions; | ||
|
|
||
| use Tempest\Auth\Exceptions\AccessWasDenied; | ||
| use Tempest\Container\Container; | ||
| use Tempest\Core\AppConfig; | ||
| use Tempest\Http\GenericResponse; | ||
| use Tempest\Http\HttpRequestFailed; | ||
| use Tempest\Http\Request; | ||
| use Tempest\Http\Response; | ||
| use Tempest\Http\Responses\Invalid; | ||
| use Tempest\Http\Session\CsrfTokenDidNotMatch; | ||
| use Tempest\Http\Status; | ||
| use Tempest\Router\MatchedRoute; | ||
| use Tempest\Support\Filesystem; | ||
| use Tempest\Validation\Exceptions\ValidationFailed; | ||
| use Tempest\View\GenericView; | ||
| use Throwable; | ||
| use Whoops\Handler\PrettyPageHandler; | ||
| use Whoops\Run; | ||
|
|
||
| final readonly class HtmlExceptionRenderer | ||
| { | ||
| public function __construct( | ||
| private AppConfig $appConfig, | ||
| private Container $container, | ||
| ) {} | ||
|
|
||
| public function render(Throwable $throwable): Response | ||
| { | ||
| if ($throwable instanceof ConvertsToResponse) { | ||
| return $throwable->toResponse(); | ||
| } | ||
|
|
||
| if ($this->appConfig->environment->isLocal()) { | ||
| $whoops = $this->createHandler(); | ||
|
|
||
| return new GenericResponse( | ||
| status: Status::INTERNAL_SERVER_ERROR, | ||
| body: $whoops->handleException($throwable), | ||
| ); | ||
| } | ||
|
|
||
| return match (true) { | ||
| $throwable instanceof RouteBindingFailed => $this->renderErrorResponse(Status::NOT_FOUND), | ||
| $throwable instanceof ValidationFailed => new Invalid($throwable->subject, $throwable->failingRules), | ||
| $throwable instanceof AccessWasDenied => $this->renderErrorResponse(Status::FORBIDDEN), | ||
| $throwable instanceof HttpRequestFailed => $this->renderErrorResponse($throwable->status, $throwable), | ||
| $throwable instanceof CsrfTokenDidNotMatch => $this->renderErrorResponse(Status::UNPROCESSABLE_CONTENT), | ||
| default => $this->renderErrorResponse(Status::INTERNAL_SERVER_ERROR), | ||
| }; | ||
| } | ||
|
|
||
| private function renderErrorResponse(Status $status, ?Throwable $exception = null): Response | ||
| { | ||
| return new GenericResponse( | ||
| status: $status, | ||
| body: new GenericView(__DIR__ . '/HttpErrorResponse/error.view.php', [ | ||
| 'css' => $this->getStyleSheet(), | ||
| 'status' => $status->value, | ||
| 'title' => $status->description(), | ||
| 'message' => $exception?->getMessage() ?: match ($status) { | ||
| Status::INTERNAL_SERVER_ERROR => 'An unexpected server error occurred', | ||
| Status::NOT_FOUND => 'This page could not be found on the server', | ||
| Status::FORBIDDEN => 'You do not have permission to access this page', | ||
| Status::UNAUTHORIZED => 'You must be authenticated in to access this page', | ||
| Status::UNPROCESSABLE_CONTENT => 'The request could not be processed due to invalid data', | ||
| default => null, | ||
| }, | ||
| ]), | ||
| ); | ||
| } | ||
|
|
||
| private function getStyleSheet(): string | ||
| { | ||
| return Filesystem\read_file(__DIR__ . '/HttpErrorResponse/style.css'); | ||
| } | ||
|
|
||
| private function createHandler(): Run | ||
| { | ||
| $handler = new PrettyPageHandler(); | ||
|
|
||
| $handler->addDataTableCallback('Route', function () { | ||
| $route = $this->container->get(MatchedRoute::class); | ||
|
|
||
| if (! $route) { | ||
| return []; | ||
| } | ||
|
|
||
| return [ | ||
| 'Handler' => $route->route->handler->getDeclaringClass()->getFileName() . ':' . $route->route->handler->getName(), | ||
| 'URI' => $route->route->uri, | ||
| 'Allowed parameters' => $route->route->parameters, | ||
| 'Received parameters' => $route->params, | ||
| ]; | ||
| }); | ||
|
|
||
| $handler->addDataTableCallback('Request', function () { | ||
| $request = $this->container->get(Request::class); | ||
|
|
||
| return [ | ||
| 'URI' => $request->uri, | ||
| 'Method' => $request->method->value, | ||
| 'Headers' => $request->headers->toArray(), | ||
| 'Parsed body' => array_filter(array_values($request->body)) ? $request->body : [], | ||
| 'Raw body' => $request->raw, | ||
| ]; | ||
| }); | ||
|
|
||
| $whoops = new Run(); | ||
|
|
||
| $whoops->pushHandler($handler); | ||
|
|
||
| $whoops->writeToOutput(send: false); | ||
|
|
||
| return $whoops; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| <?php | ||
|
|
||
| namespace Tempest\Router\Exceptions; | ||
|
|
||
| use Tempest\Auth\Exceptions\AccessWasDenied; | ||
| use Tempest\Core\AppConfig; | ||
| use Tempest\Http\HttpRequestFailed; | ||
| use Tempest\Http\Response; | ||
| use Tempest\Http\Responses\Json; | ||
| use Tempest\Http\Session\CsrfTokenDidNotMatch; | ||
| use Tempest\Http\Status; | ||
| use Tempest\Validation\Exceptions\ValidationFailed; | ||
| use Tempest\Validation\Rule; | ||
| use Tempest\Validation\Validator; | ||
| use Throwable; | ||
|
|
||
| use function Tempest\Support\arr; | ||
|
|
||
| final readonly class JsonExceptionRenderer | ||
| { | ||
| public function __construct( | ||
| private AppConfig $appConfig, | ||
| private Validator $validator, | ||
| ) {} | ||
|
|
||
| public function render(Throwable $throwable): Response | ||
| { | ||
| return match (true) { | ||
| $throwable instanceof ConvertsToResponse => $throwable->toResponse(), | ||
| $throwable instanceof ValidationFailed => $this->renderValidationErrorResponse($throwable), | ||
| $throwable instanceof RouteBindingFailed => $this->renderErrorResponse(Status::NOT_FOUND), | ||
| $throwable instanceof AccessWasDenied => $this->renderErrorResponse(Status::FORBIDDEN), | ||
| $throwable instanceof HttpRequestFailed => $this->renderErrorResponse($throwable->status, $throwable), | ||
| $throwable instanceof CsrfTokenDidNotMatch => $this->renderErrorResponse(Status::UNPROCESSABLE_CONTENT), | ||
| default => $this->renderErrorResponse(Status::INTERNAL_SERVER_ERROR, $throwable), | ||
| }; | ||
| } | ||
|
|
||
| private function renderValidationErrorResponse(ValidationFailed $exception): Response | ||
| { | ||
| $errors = arr($exception->failingRules)->map( | ||
| fn (array $failingRulesForField, string $field) => arr($failingRulesForField)->map( | ||
| fn (Rule $rule) => $this->validator->getErrorMessage($rule, $field), | ||
| )->toArray(), | ||
| ); | ||
|
|
||
| return new Json([ | ||
| 'message' => $errors->first()[0], | ||
| 'errors' => $errors->toArray(), | ||
| ])->setStatus(Status::UNPROCESSABLE_CONTENT); | ||
| } | ||
|
|
||
| private function renderErrorResponse(Status $status, ?Throwable $exception = null): Response | ||
| { | ||
| return new Json( | ||
| $this->appConfig->environment->isLocal() && $exception !== null | ||
| ? [ | ||
| 'message' => static::getErrorMessage($status, $exception), | ||
| 'exception' => get_class($exception), | ||
| 'file' => $exception->getFile(), | ||
| 'line' => $exception->getLine(), | ||
| 'trace' => arr($exception->getTrace())->map( | ||
| fn ($trace) => arr($trace)->removeKeys('args')->toArray(), | ||
| )->toArray(), | ||
| ] : [ | ||
| 'message' => static::getErrorMessage($status, $exception), | ||
| ], | ||
| )->setStatus($status); | ||
| } | ||
|
|
||
| private static function getErrorMessage(Status $status, ?Throwable $exception = null): ?string | ||
| { | ||
| return ( | ||
| $exception?->getMessage() ?: match ($status) { | ||
| Status::INTERNAL_SERVER_ERROR => 'An unexpected server error occurred', | ||
| Status::NOT_FOUND => 'This page could not be found on the server', | ||
| Status::FORBIDDEN => 'You do not have permission to access this page', | ||
| Status::UNAUTHORIZED => 'You must be authenticated in to access this page', | ||
| Status::UNPROCESSABLE_CONTENT => 'The request could not be processed due to invalid data', | ||
| default => $status->description(), | ||
| } | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't we have
HtmlHttpExceptionRendererthen for consistency?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, absolutely!
Would it make sense to remove the
DeveloperExceptionHandlerand in theHtmlHttpExceptionRendererhandle to show either whooosh or the custom view?Tests for this (entire PR) is on my todo 🙂
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe, but I'd say out of scope for this PR?