From 4b81e1fc1e606944ea69062323aea37bc1f71727 Mon Sep 17 00:00:00 2001 From: osteel Date: Fri, 1 Jul 2022 17:07:06 +0100 Subject: [PATCH] improved exception content (invalid field) --- src/Exceptions/ValidationException.php | 7 ++++++- tests/Exceptions/ValidationExceptionTest.php | 10 +++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Exceptions/ValidationException.php b/src/Exceptions/ValidationException.php index dde771a..ee786c8 100644 --- a/src/Exceptions/ValidationException.php +++ b/src/Exceptions/ValidationException.php @@ -6,11 +6,12 @@ use Exception; use League\OpenAPIValidation\PSR7\Exception\ValidationFailed; +use League\OpenAPIValidation\Schema\Exception\SchemaMismatch; class ValidationException extends Exception { /** - * Build a new exception based on a ValidationFailed one. + * Build a new exception from a ValidationFailed exception. * * @param ValidationFailed $exception * @return ValidationException @@ -22,6 +23,10 @@ public static function fromValidationFailed(ValidationFailed $exception): Valida while ($exception = $exception->getPrevious()) { $message .= sprintf(': %s', $exception->getMessage()); + + if ($exception instanceof SchemaMismatch && ! empty($breadCrumb = $exception->dataBreadCrumb())) { + $message .= sprintf(' Field: %s', implode('.', $breadCrumb->buildChain())); + } } return new ValidationException($message, 0, $previous); diff --git a/tests/Exceptions/ValidationExceptionTest.php b/tests/Exceptions/ValidationExceptionTest.php index 2100a9e..418a26d 100644 --- a/tests/Exceptions/ValidationExceptionTest.php +++ b/tests/Exceptions/ValidationExceptionTest.php @@ -4,6 +4,8 @@ use Exception; use League\OpenAPIValidation\PSR7\Exception\ValidationFailed; +use League\OpenAPIValidation\Schema\BreadCrumb; +use League\OpenAPIValidation\Schema\Exception\SchemaMismatch; use Osteel\OpenApi\Testing\Exceptions\ValidationException; use Osteel\OpenApi\Testing\Tests\TestCase; @@ -11,10 +13,12 @@ class ValidationExceptionTest extends TestCase { public function testItCreatesAnExceptionFromAValidationFailedException() { - $exception = new ValidationFailed('foo', 0, new Exception('bar', 0, new Exception('baz'))); - $sut = ValidationException::fromValidationFailed($exception); + $breadCrumb = new BreadCrumb('qux'); + $previous = (new SchemaMismatch('baz'))->withBreadCrumb($breadCrumb); + $exception = new ValidationFailed('foo', 0, new Exception('bar', 0, $previous)); + $sut = ValidationException::fromValidationFailed($exception); - $this->assertEquals('foo: bar: baz', $sut->getMessage()); + $this->assertEquals('foo: bar: baz Field: qux', $sut->getMessage()); $this->assertEquals($exception, $sut->getPrevious()); } }