Add API exception handling and error response
[MAILPOET-4135]
This commit is contained in:
@@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
namespace MailPoet\Automation\API;
|
namespace MailPoet\Automation\API;
|
||||||
|
|
||||||
|
use MailPoet\Automation\Exceptions\Exception;
|
||||||
use MailPoet\Automation\WordPress;
|
use MailPoet\Automation\WordPress;
|
||||||
use ReflectionClass;
|
use ReflectionClass;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
class API {
|
class API {
|
||||||
private const PREFIX = 'mailpoet/v1/automation';
|
private const PREFIX = 'mailpoet/v1/automation';
|
||||||
@@ -45,9 +47,19 @@ class API {
|
|||||||
$this->wordPress->registerRestRoute(self::PREFIX, $route, [
|
$this->wordPress->registerRestRoute(self::PREFIX, $route, [
|
||||||
'methods' => strtoupper($method),
|
'methods' => strtoupper($method),
|
||||||
'callback' => function ($wpRequest) use ($endpoint, $method) {
|
'callback' => function ($wpRequest) use ($endpoint, $method) {
|
||||||
$request = new Request($wpRequest);
|
try {
|
||||||
return $this->endpointFactory->createEndpoint($endpoint)->$method($request);
|
$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');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
18
mailpoet/lib/Automation/API/ErrorResponse.php
Normal file
18
mailpoet/lib/Automation/API/ErrorResponse.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php declare(strict_types = 1);
|
||||||
|
|
||||||
|
namespace MailPoet\Automation\API;
|
||||||
|
|
||||||
|
class ErrorResponse extends Response {
|
||||||
|
public function __construct(
|
||||||
|
int $status,
|
||||||
|
string $message,
|
||||||
|
string $code
|
||||||
|
) {
|
||||||
|
parent::__construct(null, $status);
|
||||||
|
$this->set_data([
|
||||||
|
'code' => $code,
|
||||||
|
'message' => $message,
|
||||||
|
'data' => ['status' => $status],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user