Skip to content

Commit

Permalink
Cleaned up Error Handler
Browse files Browse the repository at this point in the history
  • Loading branch information
dmhendricks committed Dec 23, 2017
1 parent 86bc82a commit fc1372a
Showing 1 changed file with 24 additions and 22 deletions.
46 changes: 24 additions & 22 deletions src/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,35 @@
use ChrisWhite\B2\Exceptions\BadJsonException;
use ChrisWhite\B2\Exceptions\BadValueException;
use ChrisWhite\B2\Exceptions\BucketAlreadyExistsException;
use ChrisWhite\B2\Exceptions\NotFoundException;
use ChrisWhite\B2\Exceptions\FileNotPresentException;
use ChrisWhite\B2\Exceptions\BucketNotEmptyException;
use ChrisWhite\B2\Exceptions\NotFoundException;
use GuzzleHttp\Psr7\Response;

class ErrorHandler
{
protected static $mappings = [
'bad_json' => BadJsonException::class,
'bad_value' => BadValueException::class,
'duplicate_bucket_name' => BucketAlreadyExistsException::class,
'not_found' => NotFoundException::class,
'file_not_present' => FileNotPresentException::class,
'cannot_delete_non_empty_bucket' => BucketNotEmptyException::class
];

public static function handleErrorResponse(Response $response)
{
$responseJson = json_decode($response->getBody(), true);

if (isset(self::$mappings[$responseJson['code']])) {
$exceptionClass = self::$mappings[$responseJson['code']];
} else {
// We don't have an exception mapped to this response error, throw generic exception
$exceptionClass = B2Exception::class;
}

throw new $exceptionClass('Received error from B2: '.$responseJson['message']);
protected static $mappings = array(
'bad_json' => BadJsonException::class,
'bad_value' => BadValueException::class,
'duplicate_bucket_name' => BucketAlreadyExistsException::class,
'not_found' => NotFoundException::class,
'file_not_present' => FileNotPresentException::class,
'cannot_delete_non_empty_bucket' => BucketNotEmptyException::class
);

public static function handleErrorResponse(Response $response) {

$responseJson = json_decode( $response->getBody(), true );

if ( isset( self::$mappings[$responseJson['code']] ) ) {
$exceptionClass = self::$mappings[$responseJson['code']];
} else {
// We don't have an exception mapped to this response error, throw generic exception
$exceptionClass = B2Exception::class;
}

throw new $exceptionClass( sprintf( 'Received error from B2: %s. Code: %s', $responseJson['message'], $responseJson['code'] ) );

}

}

0 comments on commit fc1372a

Please sign in to comment.