| 1 |
<?php |
| 2 |
namespace Depicter\Utility; |
| 3 |
|
| 4 |
use Psr\Http\Message\ResponseInterface; |
| 5 |
|
| 6 |
|
| 7 |
class Http { |
| 8 |
|
| 9 |
public static function getErrorExceptionResponse( \Exception $exception ){ |
| 10 |
$isConnectionError = method_exists( $exception, 'getHandlerContext' ); |
| 11 |
$errorClassInstance = get_class( $exception ); |
| 12 |
|
| 13 |
$error = [ |
| 14 |
'message' => $exception->getMessage(), |
| 15 |
'detail' => $exception->getMessage(), |
| 16 |
'errCode' => $exception->getCode(), |
| 17 |
'group' => 'Exception', // name of exception group |
| 18 |
'type' => basename( str_replace('\\', '/', $errorClassInstance )), // unqualified (short) exception class name |
| 19 |
'instance' => $errorClassInstance, |
| 20 |
'context' => null, |
| 21 |
'statusCode' => 500 |
| 22 |
]; |
| 23 |
|
| 24 |
if( $isConnectionError ){ |
| 25 |
$error['message'] = __( 'Connection Error ..', 'depicter' ); |
| 26 |
$error['group'] = 'RequestException'; |
| 27 |
$error['context'] = $exception->getHandlerContext(); |
| 28 |
$error['statusCode'] = 503; |
| 29 |
} |
| 30 |
|
| 31 |
if( ! empty( $error['context']['error'] ) ){ |
| 32 |
$error['detail'] = $error['context']['error']; |
| 33 |
} |
| 34 |
if( ! empty( $error['context']['errno'] ) ){ |
| 35 |
$error['errCode'] = $error['context']['errno']; |
| 36 |
} |
| 37 |
if( $error['errCode'] == 401 ){ |
| 38 |
$error['message'] = "You are not authorized to access this resource."; |
| 39 |
} |
| 40 |
|
| 41 |
return $error; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Generate a Json response based on errors variable |
| 46 |
* |
| 47 |
* @param $errors |
| 48 |
* |
| 49 |
* @return ResponseInterface |
| 50 |
*/ |
| 51 |
public static function getErrorJson( $errors ){ |
| 52 |
$errors = (array) $errors; |
| 53 |
$statusCode = (int) ( !empty( $errors['code'] ) ? $errors['code'] : 200 ); |
| 54 |
|
| 55 |
return \Depicter::json([ |
| 56 |
'errors' => $errors |
| 57 |
])->withStatus( max( $statusCode, 200 ) ); |
| 58 |
} |
| 59 |
} |
| 60 |
|