Add API exception handling and error response

[MAILPOET-4135]
This commit is contained in:
Jan Jakes
2022-02-10 11:00:58 +01:00
committed by Veljko V
parent b2a9053fa8
commit b40f344a51
2 changed files with 32 additions and 2 deletions

View File

@@ -2,8 +2,10 @@
namespace MailPoet\Automation\API;
use MailPoet\Automation\Exceptions\Exception;
use MailPoet\Automation\WordPress;
use ReflectionClass;
use Throwable;
class API {
private const PREFIX = 'mailpoet/v1/automation';
@@ -45,9 +47,19 @@ class API {
$this->wordPress->registerRestRoute(self::PREFIX, $route, [
'methods' => strtoupper($method),
'callback' => function ($wpRequest) use ($endpoint, $method) {
$request = new Request($wpRequest);
return $this->endpointFactory->createEndpoint($endpoint)->$method($request);
try {
$request = new Request($wpRequest);
return $this->endpointFactory->createEndpoint($endpoint)->$method($request);
} catch (Throwable $e) {
return $this->convertToErrorResponse($e);
}
},
]);
}
private function convertToErrorResponse(Throwable $e): ErrorResponse {
return $e instanceof Exception
? new ErrorResponse($e->getStatusCode(), $e->getMessage(), $e->getErrorCode())
: new ErrorResponse(500, 'An unknown error occurred.', 'mailpoet_automation_unknown_error');
}
}