diff --git a/mailpoet/lib/Automation/API/API.php b/mailpoet/lib/Automation/API/API.php index 16712d15ca..cc19ca6f6c 100644 --- a/mailpoet/lib/Automation/API/API.php +++ b/mailpoet/lib/Automation/API/API.php @@ -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'); + } } diff --git a/mailpoet/lib/Automation/API/ErrorResponse.php b/mailpoet/lib/Automation/API/ErrorResponse.php new file mode 100644 index 0000000000..53432e722e --- /dev/null +++ b/mailpoet/lib/Automation/API/ErrorResponse.php @@ -0,0 +1,18 @@ +set_data([ + 'code' => $code, + 'message' => $message, + 'data' => ['status' => $status], + ]); + } +}