protected function parseClientError(HttpException $exception)
    {
        $contentType = explode(';', $exception->getResponse()->getHeaderLine('Content-Type'))[0];
        $responseBody = (string) $exception->getResponse()->getBody();

        switch ($contentType) {
            case 'application/json':
                $res = json_decode($responseBody, true);
                if (isset($res['web_service_result'])) {
                    $res = $res['web_service_result'];
                }
                $err = $res['errorList']['error'][0];
                $message = $err['errorMessage'];
                $code = $err['errorCode'];
                break;

            case 'application/xml':
                $xml = new QuiteSimpleXMLElement($responseBody);
                $xml->registerXPathNamespace('xb', 'http://com/exlibris/urm/general/xmlbeans');

                $message = $xml->text('//xb:errorMessage');
                $code = $xml->text('//xb:errorCode');
                break;

            default:
                $message = $responseBody;
                $code = '';
        }

        // The error code is often an integer, but sometimes a string,
        // so we generalize it as a string.
        $code = empty($code) ? null : (string) $code;

        if (strtolower($message) == 'invalid api key') {
            return new InvalidApiKey($message, null, $exception);
        }

        if (preg_match('/(no items?|not) found/i', $message)) {
            return new ResourceNotFound($message, $code, $exception);
        }

        return new RequestFailed($message, $code, $exception);
    }