-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy patherror-handling.php
More file actions
52 lines (43 loc) · 1.47 KB
/
error-handling.php
File metadata and controls
52 lines (43 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php declare(strict_types=1);
/**
* Error handling examples.
*
* The package catches transport errors (Guzzle exceptions) and throws
* InvalidArgumentException. JSON parse failures return an ErrorResponse
* instead of throwing.
*/
use Hyperized\Hostfact\Api\Controllers\Product;
use Hyperized\Hostfact\Api\Entity\Product as ProductEntity;
use Hyperized\Hostfact\Api\Response\ErrorResponse;
use Hyperized\Hostfact\Api\Response\ListResponse;
use Hyperized\Hostfact\Exceptions\InvalidArgumentException;
// Handle transport/connection errors
try {
$product = Product::new()->show(['Identifier' => '1']);
} catch (InvalidArgumentException $e) {
// Connection refused, timeout, DNS failure, etc.
echo 'API call failed: ' . $e->getMessage();
}
// Check for API-level errors in the response
$response = Product::new()->list(['searchfor' => 'nonexistent']);
if ($response instanceof ErrorResponse) {
// HostFact returned an error response
foreach ($response->errors as $error) {
echo 'Error: ' . $error;
}
}
if ($response instanceof ListResponse) {
// Process the results using typed entities
echo 'Found ' . count($response->entities) . ' products';
foreach ($response->entities as $product) {
assert($product instanceof ProductEntity);
echo $product->ProductName;
}
}
// You can also use the convenience methods
if ($response->isSuccess()) {
echo 'Request succeeded';
}
if ($response->isError()) {
echo 'Request failed';
}