Skip to content

Commit 8af2bcc

Browse files
committed
Make error handling more consistent
1 parent 22a574c commit 8af2bcc

File tree

4 files changed

+33
-8
lines changed

4 files changed

+33
-8
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
namespace Webtools\JsonSchemaRequest\Exceptions;
4+
5+
use Illuminate\Http\Response;
6+
use Webtools\JsonSchemaRequest\JsonSchemaValidator;
7+
8+
class ValidationException extends \Exception
9+
{
10+
public JsonSchemaValidator $validator;
11+
12+
public int $status = Response::HTTP_UNPROCESSABLE_ENTITY;
13+
14+
public function __construct(JsonSchemaValidator $validator)
15+
{
16+
parent::__construct('The given data was invalid.');
17+
$this->validator = $validator;
18+
}
19+
20+
public function report()
21+
{
22+
// Do not report this exception.
23+
}
24+
25+
public function render()
26+
{
27+
return response()->json(['errors' => $this->validator->errors()], $this->status);
28+
}
29+
}

src/JsonSchemaRequest.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Illuminate\Http\Request;
1010
use Illuminate\Http\Response;
1111
use Illuminate\Validation\ValidatesWhenResolvedTrait;
12+
use Webtools\JsonSchemaRequest\Exceptions\ValidationException;
1213

1314
class JsonSchemaRequest extends Request implements ValidatesWhenResolved
1415
{
@@ -40,10 +41,7 @@ public function setContainer(Container $container)
4041

4142
public function failedValidation(JsonSchemaValidator $validator)
4243
{
43-
throw new HttpResponseException(response()->json(
44-
['errors' => $validator->errors()],
45-
Response::HTTP_UNPROCESSABLE_ENTITY
46-
));
44+
throw new ValidationException($validator);
4745
}
4846

4947
public function validated()

src/JsonSchemaValidator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use Illuminate\Support\MessageBag;
77
use JsonSchema\Validator as SchemaValidator;
88
use JsonSchema\Constraints\Constraint;
9-
use Illuminate\Validation\ValidationException;
9+
use Webtools\JsonSchemaRequest\Exceptions\ValidationException;
1010

1111
class JsonSchemaValidator implements ValidatorContract
1212
{

tests/JsonSchemaValidatorTest.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@
22

33
namespace Webtools\JsonSchemaRequest\Tests;
44

5-
use Illuminate\Http\Exceptions\HttpResponseException;
6-
use Illuminate\Validation\ValidationException;
5+
use Webtools\JsonSchemaRequest\Exceptions\ValidationException;
76
use Webtools\JsonSchemaRequest\JsonSchemaValidator;
87
use JsonSchema\Validator;
98
use PHPUnit\Framework\TestCase;
109

11-
1210
class JsonSchemaValidatorTest extends TestCase
1311
{
1412
protected array $schema = [

0 commit comments

Comments
 (0)