• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 13724522058

07 Mar 2025 04:04PM UTC coverage: 8.175% (-0.3%) from 8.518%
13724522058

Pull #7005

github

web-flow
Merge 322407532 into 1e0bc9dc8
Pull Request #7005: fix(validation): deprecate string message for ValidationException con…

4 of 6 new or added lines in 1 file covered. (66.67%)

159 existing lines in 24 files now uncovered.

12839 of 157045 relevant lines covered (8.18%)

13.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/docs/guides/error-provider.php
1
<?php
2
// ---
3
// slug: error-provider
4
// name: Error provider to translate exception messages
5
// position: 7
6
// executable: true
7
// tags: design, state
8
// ---
9

10
namespace App\ApiResource {
11
    use ApiPlatform\Metadata\ApiResource;
12
    use ApiPlatform\Metadata\Get;
13
    use ApiPlatform\Metadata\Operation;
14
    use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
15

16
    #[ApiResource(
17
        operations: [
×
18
            new Get(provider: Book::class.'::provide'),
×
19
        ],
×
20
    )]
×
21
    class Book
22
    {
23
        public function __construct(
24
            public readonly int $id = 1,
25
            public readonly string $name = 'Anon',
26
        ) {
27
        }
×
28

29
        public static function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
30
        {
31
            throw new BadRequestHttpException('something is not right');
×
32
        }
33
    }
34
}
35

36
namespace App\State {
37
    use ApiPlatform\Metadata\Operation;
38
    use ApiPlatform\State\ApiResource\Error;
39
    use ApiPlatform\State\ProviderInterface;
40

41
    // Note that we need to replace the "api_platform.state.error_provider" service, this is done later in this guide.
42
    final class ErrorProvider implements ProviderInterface
43
    {
44
        public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
45
        {
46
            $request = $context['request'];
×
47
            if (!$request || !($exception = $request->attributes->get('exception'))) {
×
48
                throw new \RuntimeException();
×
49
            }
50

51
            /** @var \ApiPlatform\Metadata\HttpOperation $operation */
52
            $status = $operation->getStatus() ?? 500;
×
53
            // You don't have to use this, you can use a Response, an array or any object (preferably a resource that API Platform can handle).
54
            $error = Error::createFromException($exception, $status);
×
55

56
            // care about hiding informations as this can be a security leak
57
            if ($status >= 500) {
×
58
                $error->setDetail('Something went wrong');
×
59
            } else {
60
                // You can handle translation here with the [Translator](https://symfony.com/doc/current/translation.html)
61
                $error->setDetail(str_replace('something is not right', 'les calculs ne sont pas bons', $exception->getMessage()));
×
62
            }
63

64
            return $error;
×
65
        }
66
    }
67
}
68

69
// This is replacing the service, the "key" is important as this is the provider we
70
// will look for when handling an exception.
71

72
namespace App\DependencyInjection {
73
    use App\State\ErrorProvider;
74
    use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
75

76
    function configure(ContainerConfigurator $configurator): void
77
    {
78
        $services = $configurator->services();
×
79
        $services->set('api_platform.state.error_provider')
×
80
            ->class(ErrorProvider::class)
×
81
            ->tag('api_platform.state_provider', ['key' => 'api_platform.state.error_provider']);
×
82
    }
83
}
84

85
namespace App\Tests {
86
    use ApiPlatform\Playground\Test\TestGuideTrait;
87
    use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
88

89
    final class BookTest extends ApiTestCase
90
    {
91
        use TestGuideTrait;
92

93
        public function testBookDoesNotExists(): void
94
        {
95
            static::createClient()->request('GET', '/books/1', options: ['headers' => ['accept' => 'application/ld+json']]);
×
96
            $this->assertResponseStatusCodeSame(400);
×
97
            $this->assertJsonContains([
×
98
                'detail' => 'les calculs ne sont pas bons',
×
99
            ]);
×
100
        }
101
    }
102
}
103

104
namespace App\Playground {
105
    use Symfony\Component\HttpFoundation\Request;
106

107
    function request(): Request
108
    {
109
        return Request::create('/books/1.jsonld', 'GET');
×
110
    }
111
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc