Laranudge logo
Dashboard

Manage your nudges with skill

Craft a nudge

Submit a new one to guide the way

Most loved nudges

The most popular nudges

Profile

Tend to your profile with finesse

Php Hook To Handle Try & Catch Blocks

Use a custom hook helper function to easily catch repetitive try & catch instructions

        
1// Before
2private static function setHttpResponse(string $method, string $url, array $body = []): GuzzleHttpPsr7Response
3{
4 static::setRequestOptions();
5 
6 try {
7 static::$response = static::$client->{strtolower($method)}(
8 NotchPay::$apiBase . '/' . $url,
9 ['body' => json_encode($body)]
10 );
11 } catch (ClientException | ServerExceptionn | ConnectException $e ) {
12 if($e instanceof ConnectException) {
13 throw new ApiException(`Notch Pay Server unreachable`);
14 }
15 throw new ApiException(self::getResponseErrorMessage($e), self::getResponseErrors($e));
16 }
17 
18 return static::$response;
19}
20 
21// Create a try catch hook helper function
22 
23if (! function_exists('useTryCatch')) {
24 function useTryCatch(Closure $closure, ?Closure $catchable = null): array
25 {
26 $result = null;
27 $throwable = null;
28 
29 $catch = $catchable ?? fn (Throwable $exception) => $exception;
30 
31 try {
32 $result = $closure();
33 } catch (Throwable $exception) {
34 $throwable = $catch($exception);
35 }
36 
37 return [$throwable, $result];
38 }
39}
40 
41// After
42private static function setHttpResponse(string $method, string $url, array $body = []): GuzzleHttpPsr7Response
43{
44 static::setRequestOptions();
45 
46 [$throwable, $result] = useTryCatch(fn () => static::$client->{strtolower($method)}(
47 NotchPay::$apiBase . '/' . $url,
48 ['body' => json_encode($body)]
49 ));
50 
51 if($throwable instanceof ConnectException) {
52 throw new ApiException(`Notch Pay Server unreachable`);
53 }
54 
55 
56 return $result;
57}
0
This impeccable nudge was posted 1 month ago