Add functionality for converting exceptions to HTTP responses

[MAILPOET-2900]
This commit is contained in:
Jan Jakeš
2020-05-07 18:39:35 +02:00
committed by Veljko V
parent d11dc98190
commit 3f78c82c51
7 changed files with 153 additions and 10 deletions

View File

@ -0,0 +1,27 @@
<?php declare(strict_types = 1);
namespace MailPoet\API\JSON;
use MailPoet\Exception;
use MailPoet\HttpAwareException;
use MailPoet\WP\Functions as WPFunctions;
class ErrorHandler {
/** @var string[] */
private $defaultErrors;
public function __construct(WPFunctions $wp) {
$this->defaultErrors = [
Error::UNKNOWN => $wp->__('An unknown error occurred.', 'mailpoet'),
];
}
public function convertToResponse(\Throwable $e): ErrorResponse {
if ($e instanceof Exception) {
$errors = $e->getErrors() ?: $this->defaultErrors;
$statusCode = $e instanceof HttpAwareException ? $e->getHttpStatusCode() : Response::STATUS_UNKNOWN;
return new ErrorResponse($errors, [], $statusCode);
}
return new ErrorResponse($this->defaultErrors, [], Response::STATUS_UNKNOWN);
}
}