Skip to content

Commit 1fa8c05

Browse files
authored
fix(validator): fallback to message when detail is uninitialized (#7844)
Closes #7843
1 parent 01e3a1b commit 1fa8c05

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/State/Tests/ErrorProviderTest.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,33 @@
1414
namespace ApiPlatform\State\Tests;
1515

1616
use ApiPlatform\Metadata\Get;
17+
use ApiPlatform\State\ApiResource\Error;
1718
use ApiPlatform\State\ErrorProvider;
19+
use ApiPlatform\Validator\Exception\ValidationException;
1820
use PHPUnit\Framework\TestCase;
1921
use Symfony\Component\HttpFoundation\Request;
22+
use Symfony\Component\Validator\ConstraintViolation;
23+
use Symfony\Component\Validator\ConstraintViolationList;
2024

2125
class ErrorProviderTest extends TestCase
2226
{
27+
public function testCreateFromExceptionWithValidationException(): void
28+
{
29+
$violation = new ConstraintViolation('This value is too long.', null, [], null, 'name', 'toolong');
30+
$exception = new ValidationException(new ConstraintViolationList([$violation]));
31+
$error = Error::createFromException($exception, 422);
32+
33+
$this->assertSame('An error occurred', $error->getTitle());
34+
$this->assertSame($exception->getMessage(), $error->getDetail());
35+
$this->assertSame(422, $error->getStatus());
36+
}
37+
2338
public function testErrorProviderProduction(): void
2439
{
2540
$provider = new ErrorProvider(debug: false);
2641
$request = Request::create('/');
2742
$request->attributes->set('exception', new \Exception());
28-
/** @var \ApiPlatform\State\ApiResource\Error */
43+
/** @var Error */
2944
$error = $provider->provide(new Get(), [], ['request' => $request]);
3045
$this->assertEquals('Internal Server Error', $error->getDetail());
3146
}

src/Validator/Exception/ValidationException.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ public function __construct(string|ConstraintViolationListInterface $message = n
111111
if ($message instanceof ConstraintViolationListInterface) {
112112
$this->constraintViolationList = $message;
113113
parent::__construct($this->__toString(), $code ?? 0, $previous);
114+
$this->detail = $this->getMessage();
114115

115116
return;
116117
}
@@ -119,6 +120,7 @@ public function __construct(string|ConstraintViolationListInterface $message = n
119120

120121
trigger_deprecation('api_platform/core', '5.0', \sprintf('The "%s" exception will have a "%s" first argument in 5.x.', self::class, ConstraintViolationListInterface::class));
121122
parent::__construct($message ?: $this->__toString(), $code ?? 0, $previous);
123+
$this->detail = $this->getMessage();
122124
}
123125

124126
public function getId(): string

0 commit comments

Comments
 (0)