core: Wrong error code when denormalizing a non existant item

API Platform version(s) affected: 3.2.11

Description
While writing tests I noticed that when you try to denormalize a non existing item it’ll throw an exception with statuscode 500.

It shouldn’t error out with a 500 error since that’s not the expected error code for cases like that.

How to reproduce

#[ApiResource]
class Foo {
   prive ?Bar $bar = null;
}
#[ApiResource]
class Bar {
}

and then try to create a Foo with a reference to a non existing Bar. Possible Solution

There’s two solutions for this: Change the error code to 404, to match the not found paradime.

Optionally allow not found items to serialize to null so users can throw their own errors with Validations.

Additional Context

    "title": "An error occurred",
    "detail": "Item not found for \"/api/bar/018d1ca6-da89-77c2-93a9-2b3593055e42\".",
    "status": 500,
    "type": "/errors/500",
    "trace": [
        {
            "file": "/app/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
            "line": 860,
            "function": "denormalizeRelation",
            "class": "ApiPlatform\\Serializer\\AbstractItemNormalizer",
            "type": "->"
        },
...

About this issue

  • Original URL
  • State: open
  • Created 5 months ago
  • Comments: 16 (15 by maintainers)

Commits related to this issue

Most upvoted comments

Like the test setup seems to be flawed in a way. Looking into it more it throws Invalid Iri in AbstractItemNormalizer.php:572 because no route matches "/issue6116_relation/1". The route should exist but shouldn’t find the resource.

What you got now seems to be just a non existing route for some reason

Same issue with a backed enum:

Example:

<?php

enum StatusEnum: string {
    case Ready: 'ready';
}

class MyEntity {
    private ?StatusEnum $status = null;

    public function getStatus(): ?StatusEnum
    {
        return $this->status;
    }

    public function setStatus(StatusEnum $status): static
    {
        $this->status = $status;

        return $this;
    }
}

Making a POST request with:

{
    "status": "unknown_status",
}

Will result in an Error 500:

{
    "@context": "\/api\/contexts\/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "The data must belong to a backed enumeration of type App\\Enum\\StatusEnum",
    "trace": [
        // ...
    ]
}