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

Custom error handler #153

Merged
merged 10 commits into from
Nov 16, 2024
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip
* [BC] DefaultHandler response code 404 instead 400
* [BC] Added Container to API Decider
* [BC] Output Configurator, Allows different methods for output configuration. Needs to be added to config services.
* [BC] Error handler, Allows for custom error handling of handle method. Needs to be added to config services.
* Query configurator rework

#### Added
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,20 @@ application:
Api: Tomaj\NetteApi\Presenters\*Presenter
```

Then register your preffered output configurator in *config.neon* services:
Register your preferred output configurator in *config.neon* services:

```neon
services:
apiOutputConfigurator: Tomaj\NetteApi\Output\Configurator\DebuggerConfigurator
```

Register your preferred error handler in *config.neon* services:

```neon
services:
apiErrorHandler: Tomaj\NetteApi\Error\DefaultErrorHandler
```

And add route to you RouterFactory:

```php
Expand Down
66 changes: 66 additions & 0 deletions src/Error/DefaultErrorHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Error;

use Nette\Http\Response;
use Throwable;
use Tomaj\NetteApi\Authorization\ApiAuthorizationInterface;
use Tomaj\NetteApi\Output\Configurator\ConfiguratorInterface;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tracy\Debugger;

final class DefaultErrorHandler implements ErrorHandlerInterface
{
/** @var ConfiguratorInterface */
private $outputConfigurator;

public function __construct(ConfiguratorInterface $outputConfigurator)
{
$this->outputConfigurator = $outputConfigurator;
}

public function handle(Throwable $exception, array $params): JsonApiResponse
{
Debugger::log($exception, Debugger::EXCEPTION);
if ($this->outputConfigurator->showErrorDetail()) {
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error', 'detail' => $exception->getMessage()]);
} else {
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error']);
}
return $response;
}

public function handleInputParams(array $errors): JsonApiResponse
{
if ($this->outputConfigurator->showErrorDetail()) {
$response = new JsonApiResponse(Response::S400_BAD_REQUEST, ['status' => 'error', 'message' => 'wrong input', 'detail' => $errors]);
} else {
$response = new JsonApiResponse(Response::S400_BAD_REQUEST, ['status' => 'error', 'message' => 'wrong input']);
}
return $response;
}

public function handleSchema(array $errors, array $params): JsonApiResponse
{
Debugger::log($errors, Debugger::ERROR);

if ($this->outputConfigurator->showErrorDetail()) {
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error', 'detail' => $errors]);
} else {
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error']);
}
return $response;
}

public function handleAuthorization(ApiAuthorizationInterface $auth, array $params): JsonApiResponse
{
return new JsonApiResponse(Response::S401_UNAUTHORIZED, ['status' => 'error', 'message' => $auth->getErrorMessage()]);
}

public function handleAuthorizationException(Throwable $exception, array $params): JsonApiResponse
{
return new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => $exception->getMessage()]);
}
}
39 changes: 39 additions & 0 deletions src/Error/ErrorHandlerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Error;

use Tomaj\NetteApi\Authorization\ApiAuthorizationInterface;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Throwable;

interface ErrorHandlerInterface
{
/**
* @param array<mixed> $params
*/
public function handle(Throwable $exception, array $params): JsonApiResponse;

/**
* @param array<string> $errors
* @param array<mixed> $params
*/
public function handleInputParams(array $errors): JsonApiResponse;

/**
* @param array<string> $errors
* @param array<mixed> $params
*/
public function handleSchema(array $errors, array $params): JsonApiResponse;

/**
* @param array<mixed> $params
*/
public function handleAuthorization(ApiAuthorizationInterface $auth, array $params): JsonApiResponse;

/**
* @param array<mixed> $params
*/
public function handleAuthorizationException(Throwable $exception, array $params): JsonApiResponse;
Martin-Beranek marked this conversation as resolved.
Show resolved Hide resolved
}
54 changes: 28 additions & 26 deletions src/Presenters/ApiPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@
use Tomaj\NetteApi\Api;
use Tomaj\NetteApi\ApiDecider;
use Tomaj\NetteApi\Authorization\ApiAuthorizationInterface;
use Tomaj\NetteApi\Error\ErrorHandlerInterface;
use Tomaj\NetteApi\Logger\ApiLoggerInterface;
use Tomaj\NetteApi\Misc\IpDetectorInterface;
use Tomaj\NetteApi\Output\Configurator\ConfiguratorInterface;
use Tomaj\NetteApi\Output\OutputInterface;
use Tomaj\NetteApi\Params\ParamsProcessor;
use Tomaj\NetteApi\RateLimit\RateLimitInterface;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tracy\Debugger;
use Tomaj\NetteApi\Output\Configurator\ConfiguratorInterface;

final class ApiPresenter implements IPresenter
{
Expand All @@ -37,6 +36,9 @@ final class ApiPresenter implements IPresenter
/** @var ConfiguratorInterface @inject */
public $outputConfigurator;

/** @var ErrorHandlerInterface @inject */
public $errorHandler;

/**
* CORS header settings
*
Expand Down Expand Up @@ -71,30 +73,28 @@ public function run(Request $request): IResponse

$api = $this->getApi($request);
$handler = $api->getHandler();

$authorization = $api->getAuthorization();
$rateLimit = $api->getRateLimit();

$authResponse = $this->checkAuth($authorization);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

preco sme presunuli autorizaciu az za parametre a rate limit?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lebo treba spracovat parametre aby som mal dostupny Context do erroru. Nepacilo sa mi to ale lepsie som nevymyslel.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm už si spomínam. Len teraz úplne zmeníme výstupy - ak niečo predtým padlo už na autorizácii, alebo rate limite parametre sa vôbec neriešili. Teraz to bude naopak a neviem povedať ci korektne.

if ($authResponse !== null) {
return $authResponse;
}

$rateLimitResponse = $this->checkRateLimit($rateLimit);
if ($rateLimitResponse !== null) {
return $rateLimitResponse;
}

$paramsProcessor = new ParamsProcessor($handler->params());
if ($paramsProcessor->isError()) {
$this->response->setCode(Response::S400_BAD_REQUEST);
if ($this->outputConfigurator->showErrorDetail()) {
$response = new JsonResponse(['status' => 'error', 'message' => 'wrong input', 'detail' => $paramsProcessor->getErrors()]);
} else {
$response = new JsonResponse(['status' => 'error', 'message' => 'wrong input']);
}
$response = $this->errorHandler->handleInputParams($paramsProcessor->getErrors());
$this->response->setCode($response->getCode());
return $response;
}
$params = $paramsProcessor->getValues();

$authResponse = $this->checkAuth($authorization, $params);
if ($authResponse !== null) {
return $authResponse;
}

try {
$response = $handler->handle($params);
$code = $response->getCode();
Expand All @@ -116,18 +116,13 @@ public function run(Request $request): IResponse
$outputValidatorErrors[] = $validationResult->getErrors();
}
if (!$outputValid) {
Debugger::log($outputValidatorErrors, Debugger::ERROR);
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error', 'details' => $outputValidatorErrors]);
$response = $this->errorHandler->handleSchema($outputValidatorErrors, $params);
$code = $response->getCode();
}
}
} catch (Throwable $exception) {
if ($this->outputConfigurator->showErrorDetail()) {
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error', 'detail' => $exception->getMessage()]);
} else {
$response = new JsonApiResponse(Response::S500_INTERNAL_SERVER_ERROR, ['status' => 'error', 'message' => 'Internal server error']);
}
$response = $this->errorHandler->handle($exception, $params);
$code = $response->getCode();
Debugger::log($exception, Debugger::EXCEPTION);
}

$end = microtime(true);
Expand All @@ -153,11 +148,18 @@ private function getApi(Request $request): Api
);
}

private function checkAuth(ApiAuthorizationInterface $authorization): ?IResponse
private function checkAuth(ApiAuthorizationInterface $authorization, array $params): ?IResponse
{
if (!$authorization->authorized()) {
$this->response->setCode(Response::S403_FORBIDDEN);
return new JsonResponse(['status' => 'error', 'message' => $authorization->getErrorMessage()]);
try {
if (!$authorization->authorized()) {
$response = $this->errorHandler->handleAuthorization($authorization, $params);
$this->response->setCode($response->getCode());
return $response;
}
} catch (Throwable $exception) {
$response = $this->errorHandler->handleAuthorizationException($exception, $params);
$this->response->setCode($response->getCode());
return $response;
}
return null;
}
Expand Down
5 changes: 5 additions & 0 deletions tests/Presenters/ApiPresenterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Tomaj\NetteApi\Authorization\BearerTokenAuthorization;
use Tomaj\NetteApi\Authorization\NoAuthorization;
use Tomaj\NetteApi\EndpointIdentifier;
use Tomaj\NetteApi\Error\DefaultErrorHandler;
use Tomaj\NetteApi\Handlers\AlwaysOkHandler;
use Tomaj\NetteApi\Handlers\EchoHandler;
use Tomaj\NetteApi\Misc\IpDetector;
Expand Down Expand Up @@ -41,6 +42,7 @@ public function testSimpleResponse()
$presenter->response = new HttpResponse();
$presenter->context = new Container();
$presenter->outputConfigurator = new DebuggerConfigurator();
$presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator);

$request = new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'test', 'apiAction' => 'api']);
$result = $presenter->run($request);
Expand All @@ -65,6 +67,7 @@ public function testWithAuthorization()
$presenter->response = new HttpResponse();
$presenter->context = new Container();
$presenter->outputConfigurator = new DebuggerConfigurator();
$presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator);

$request = new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'test', 'apiAction' => 'api']);
$result = $presenter->run($request);
Expand All @@ -87,6 +90,7 @@ public function testWithParams()
$presenter->response = new HttpResponse();
$presenter->context = new Container();
$presenter->outputConfigurator = new DebuggerConfigurator();
$presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator);

Debugger::$productionMode = Debugger::PRODUCTION;

Expand Down Expand Up @@ -117,6 +121,7 @@ public function testWithOutputs()
$presenter->response = new HttpResponse();
$presenter->context = new Container();
$presenter->outputConfigurator = new DebuggerConfigurator();
$presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator);

$request = new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'test', 'apiAction' => 'api']);
$result = $presenter->run($request);
Expand Down
Loading