Skip to content

Commit da59df5

Browse files
author
Aman Alam
authored
Merge pull request #21 from TechhDan/exception-bug-fix
Allow standard exception to handle strings for JSON API responses
2 parents 1250294 + 3db5720 commit da59df5

File tree

2 files changed

+59
-18
lines changed

2 files changed

+59
-18
lines changed

lib/PaymentRails/Exception/Standard.php

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,33 @@
44
use PaymentRails\Exception;
55

66
/**
7-
* Raised when a standard error request is received
8-
*
9-
* @package PaymentRails
10-
* @subpackage Exception
11-
*/
7+
* Raised when a standard error request is received
8+
*
9+
* @package PaymentRails
10+
* @subpackage Exception
11+
*/
1212
class Standard extends Exception
1313
{
14-
protected $errorBody;
14+
protected $errorBody;
1515

16-
public function __construct($errorBody)
17-
{
18-
$message = "";
19-
foreach ($errorBody as $e) {
20-
if (isset($e['field'])) {
21-
$message = $message . $e['code'] . ": " . $e['message'] . " (field: '" . $e['field'] . "') \n";
22-
} else {
23-
$message = $message . $e['code'] . ": " . $e['message'] . "\n";
24-
}
25-
}
26-
$this->message = $message;
27-
}
16+
/**
17+
* @var $errorBody string|array
18+
*/
19+
public function __construct($errorBody)
20+
{
21+
$message = '';
22+
if (is_array($errorBody)) {
23+
foreach($errorBody as $e) {
24+
$message .= "{$e['code']}: {$e['message']}";
25+
if (!empty($e['field'])) {
26+
$message .= " (field: {$e['field']})";
27+
}
28+
$message .= "\n";
29+
}
30+
} elseif (is_string($errorBody)) {
31+
$message = $errorBody;
32+
}
33+
$this->message = $message;
34+
}
2835
}
2936
class_alias('PaymentRails\Exception\Standard', 'PaymentRails_Exception_Standard');

tests/Exception/StandardTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
use PHPUnit\Framework\TestCase;
4+
use PaymentRails\Exception\Standard;
5+
6+
class StandardTest extends TestCase
7+
{
8+
public function testExceptionWithString()
9+
{
10+
$this->expectException(Standard::class);
11+
$this->expectExceptionMessage('unknown');
12+
throw new Standard('unknown');
13+
}
14+
15+
public function testExceptionWithArray()
16+
{
17+
$errorBody = array(
18+
array(
19+
'code' => 404,
20+
'message' => 'not found',
21+
'field' => 'text'
22+
),
23+
array(
24+
'code' => 202,
25+
'message' => 'success'
26+
)
27+
);
28+
$this->expectException(Standard::class);
29+
$this->expectExceptionMessage(
30+
"404: not found (field: text)\n202: success\n"
31+
);
32+
throw new Standard($errorBody);
33+
}
34+
}

0 commit comments

Comments
 (0)