Skip to content

Commit

Permalink
Gracefully handling XML parse errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mtdowling committed May 26, 2015
1 parent f7a45e6 commit 757812d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/Aws/Common/Exception/Parser/DefaultXmlExceptionParser.php
Expand Up @@ -24,9 +24,6 @@
*/
class DefaultXmlExceptionParser implements ExceptionParserInterface
{
/**
* {@inheritdoc}
*/
public function parse(RequestInterface $request, Response $response)
{
$data = array(
Expand All @@ -37,13 +34,25 @@ public function parse(RequestInterface $request, Response $response)
'parsed' => null
);

if ($body = $response->getBody(true)) {
$this->parseBody(new \SimpleXMLElement($body), $data);
} else {
$body = $response->getBody(true);

if (!$body) {
$this->parseHeaders($request, $response, $data);
return $data;
}

return $data;
try {
$xml = new \SimpleXMLElement($body);
$this->parseBody($xml, $data);
return $data;
} catch (\Exception $e) {
// Gracefully handle parse errors. This could happen when the
// server responds with a non-XML response (e.g., private beta
// services).
$data['code'] = 'PhpInternalXmlParseError';
$data['message'] = 'A non-XML response was received';
return $data;
}
}

/**
Expand Down
Expand Up @@ -101,4 +101,15 @@ public function testParsesResponsesWithNoBody()
$this->assertEquals('400 Bad Request (Request-ID: Foo)', $result['message']);
$this->assertEquals('Foo', $result['request_id']);
}

public function testGracefullyHandlesInvalidXmlResponse()
{
$request = new Request('GET', 'http://example.com');
$response = Response::fromMessage("HTTP/1.1 400 Bad Request\r\n\r\nThis is not XML!");
$parser = new DefaultXmlExceptionParser();
$result = $parser->parse($request, $response);
$this->assertEquals('A non-XML response was received', $result['message']);
$this->assertEquals('PhpInternalXmlParseError', $result['code']);
$this->assertNull($result['request_id']);
}
}

0 comments on commit 757812d

Please sign in to comment.