Skip to content

Commit 767fbdd

Browse files
committed
fix: reset format when an error occurs
1 parent b179302 commit 767fbdd

File tree

3 files changed

+37
-3
lines changed

3 files changed

+37
-3
lines changed

src/Symfony/EventListener/ErrorListener.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,9 @@ public function __construct(
6868
protected function duplicateRequest(\Throwable $exception, Request $request): Request
6969
{
7070
$format = $this->getRequestFormat($request, $this->errorFormats, false);
71-
// Because ErrorFormatGuesser is buggy in some cases
72-
$request->setRequestFormat($format);
71+
// Reset the request format as it may be that the original request format negotiation won't have the same result
72+
// when an error occurs
73+
$request->setRequestFormat(null);
7374
$apiOperation = $this->initializeOperation($request);
7475

7576
// TODO: add configuration flag to:
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource;
15+
16+
use ApiPlatform\Metadata\Post;
17+
18+
#[Post(inputFormats: ['xml' => 'application/xml'], uriVariables: ['id'])]
19+
class XmlWithJsonError
20+
{
21+
}

tests/Functional/ErrorTest.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use ApiPlatform\State\ApiResource\Error;
1717
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
18+
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\XmlWithJsonError;
1819
use ApiPlatform\Tests\SetupClassResourcesTrait;
1920
use PHPUnit\Framework\Attributes\DataProvider;
2021

@@ -29,7 +30,7 @@ final class ErrorTest extends ApiTestCase
2930
*/
3031
public static function getResources(): array
3132
{
32-
return [Error::class];
33+
return [Error::class, XmlWithJsonError::class];
3334
}
3435

3536
#[DataProvider('formatsProvider')]
@@ -79,4 +80,15 @@ public static function formatsProvider(): array
7980
],
8081
];
8182
}
83+
84+
public function testJsonError(): void
85+
{
86+
self::createClient()->request('POST', '/xml_with_json_errors', [
87+
'headers' => ['content-type' => 'application/json'],
88+
'body' => '<xml></xml>',
89+
]);
90+
91+
$this->assertResponseStatusCodeSame(415);
92+
$this->assertJsonContains(['detail' => 'The content-type "application/json" is not supported. Supported MIME types are "application/xml".']);
93+
}
8294
}

0 commit comments

Comments
 (0)