diff --git a/src/Mailgun/Exception/HttpClientException.php b/src/Mailgun/Exception/HttpClientException.php index 5c0eb1d..da50873 100644 --- a/src/Mailgun/Exception/HttpClientException.php +++ b/src/Mailgun/Exception/HttpClientException.php @@ -55,7 +55,21 @@ final class HttpClientException extends \RuntimeException implements Exception public static function badRequest(ResponseInterface $response = null) { - return new self('The parameters passed to the API were invalid. Check your inputs!', 400, $response); + $message = 'The parameters passed to the API were invalid. Check your inputs!'; + + if (null !== $response) { + $body = $response->getBody()->__toString(); + if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) { + $validationMessage = $body; + } else { + $jsonDecoded = json_decode($body, true); + $validationMessage = isset($jsonDecoded['message']) ? $jsonDecoded['message'] : $body; + } + + $message = sprintf("%s\n\n%s", $message, $validationMessage); + } + + return new self($message, 400, $response); } public static function unauthorized(ResponseInterface $response = null) diff --git a/tests/Exception/HttpClientExceptionTest.php b/tests/Exception/HttpClientExceptionTest.php new file mode 100644 index 0000000..33e53d8 --- /dev/null +++ b/tests/Exception/HttpClientExceptionTest.php @@ -0,0 +1,35 @@ + 'application/json'], '{"message":"Server Message"}'); + $exception = HttpClientException::badRequest($response); + $this->assertStringEndsWith('Server Message', $exception->getMessage()); + + $response = new Response(400, ['Content-Type' => 'application/json'], '{"Foo":"Server Message"}'); + $exception = HttpClientException::badRequest($response); + $this->assertStringEndsWith('{"Foo":"Server Message"}', $exception->getMessage()); + } + + public function testBadRequestGetMessage() + { + $response = new Response(400, ['Content-Type' => 'text/html'], 'Server HTML'); + $exception = HttpClientException::badRequest($response); + $this->assertStringEndsWith('Server HTML', $exception->getMessage()); + } +}