PluginProbe
Metricool – Social media and site statistics / trunk
Metricool – Social media and site statistics vtrunk
2.1.0 2.0.2 2.0.1 2.0.0 1.27 trunk
metricool / app / Http / Metricool / Exceptions / ApiException.php

ApiException.php in Metricool – Social media and site statistics trunk, at app/Http/Metricool/Exceptions/ApiException.php

65 lines 1.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Metricool\Http\Metricool\Exceptions;
6
7 /**
8 * Class is used to wrap the exceptions caught in {@see MetricoolClient} and is
9 * used to normalize the upstream HTTP status codes.
10 */
11 class ApiException extends \Exception
12 {
13 /**
14 * The default upstream HTTP status code to use when the upstream HTTP
15 * status code is missing or a server error (5xx).
16 */
17 private const DEFAULT_UPSTREAM_SERVER_ERROR = 503;
18
19 /**
20 * Optional storage for additional data. Can be used to pass data about the
21 * failed request to the exception handler via {@see setData()}
22 * and {@see getData()}
23 */
24 protected array $data = [];
25
26 public function __construct(string $message = '', int $code = 0, ?\Throwable $previous = null)
27 {
28 $code = $this->normalizeCode($code);
29
30 parent::__construct($message, $code, $previous);
31 }
32
33 /**
34 * Method to map all missing codes or server errors to
35 * {@see DEFAULT_UPSTREAM_SERVER_ERROR}.
36 */
37 protected function normalizeCode(int $code): int
38 {
39 $isServerError = ($code >= 500 && $code <= 599);
40
41 if (!empty($code) && !$isServerError) {
42 return $code;
43 }
44
45 return self::DEFAULT_UPSTREAM_SERVER_ERROR;
46 }
47
48 /**
49 * Set additional exception {@see data}.
50 */
51 public function setData(array $data): ApiException
52 {
53 $this->data = $data;
54 return $this;
55 }
56
57 /**
58 * Get additional exception {@see data}.
59 */
60 public function getData(): array
61 {
62 return $this->data;
63 }
64 }
65