Skip to content

Commit 3cf33b0

Browse files
committed
json error
1 parent a45c512 commit 3cf33b0

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/JsonResponse.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
namespace Valar;
77

8+
use Mvc5\Exception;
9+
810
class JsonResponse
911
extends Response
1012
{
@@ -21,7 +23,17 @@ class JsonResponse
2123
function __construct($data, $status = 200, array $headers = [])
2224
{
2325
parent::__construct(
24-
json_encode($data, static::ENCODE_OPTIONS), $status, $headers + ['content-type' => 'application/json']
26+
$this->result(json_encode($data, static::ENCODE_OPTIONS)), $status, $headers + ['content-type' => 'application/json']
2527
);
2628
}
29+
30+
/**
31+
* @param $result
32+
* @return string
33+
*/
34+
protected function result($result) : string
35+
{
36+
return JSON_ERROR_NONE === json_last_error() ? $result :
37+
Exception::invalidArgument('JSON Encode Error: ' . json_last_error_msg());
38+
}
2739
}

src/Stream/JsonStream.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
namespace Valar\Stream;
77

8+
use Mvc5\Exception;
89
use Zend\Diactoros\Stream;
910

1011
class JsonStream
@@ -21,7 +22,17 @@ class JsonStream
2122
function __construct($data)
2223
{
2324
parent::__construct('php://memory', 'wb+');
24-
$this->write(json_encode($data, static::ENCODE_OPTIONS));
25+
$this->write($this->result(json_encode($data, static::ENCODE_OPTIONS)));
2526
$this->rewind();
2627
}
28+
29+
/**
30+
* @param $result
31+
* @return string
32+
*/
33+
protected function result($result) : string
34+
{
35+
return JSON_ERROR_NONE === json_last_error() ? $result :
36+
Exception::invalidArgument('JSON Encode Error: ' . json_last_error_msg());
37+
}
2738
}

0 commit comments

Comments
 (0)