Add API exception handling and error response
[MAILPOET-4135]
This commit is contained in:
@@ -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');
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user