Skip to content

Commit

Permalink
Merge pull request #21 from osteel/feature/improve-exception-content
Browse files Browse the repository at this point in the history
Improved exception content (invalid field)
  • Loading branch information
osteel authored Jul 1, 2022
2 parents 91e872f + 4b81e1f commit f0fc193
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
7 changes: 6 additions & 1 deletion src/Exceptions/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand Down
10 changes: 7 additions & 3 deletions tests/Exceptions/ValidationExceptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@

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;

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());
}
}

0 comments on commit f0fc193

Please sign in to comment.