craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 57 forks source link

Element API endpoints now always throw 500 instead of 404 error #157

Closed linusschwab closed 2 years ago

linusschwab commented 3 years ago

Description

After updating to the newest version of Element API, the endpoints now always throw a 500 instead of a 404 error if the element query returns no results.

I think this was introduced in version 2.8.1 according to the releasenotes: "Fixed a bug where most exceptions were resulting in 404 responses rather than 500s".

Is this change intentional like that and expected behaviour? If so, what needs to be changed for it to throw 404 errors again if an element is not found? As a workaround, we temporary downgraded to version 2.7.0, where this works as expected.

Let me know if you need any additional information.

Steps to reproduce

  1. Create a simple test endpoint with a simple transformer function, for example:
    'pages/<lang:{handle}>/<slug:{slug}>' => function ($lang, $slug) {
    return [
    'one' => true,
    'criteria' => [
      'section' => 'pages',
      'site' => $lang,
      'slug' => $slug
    ],
    'transformer' => function (craft\elements\Entry $entry) {
      return [
        'title' => $entry->title,
        'url' => $entry->url
     ];
    }
    ];
    }
  2. Send a request with an invalid slug or site handle, where no element matches the criteria. Instead of a 404, a 500 error is returned. Expected would be a 404 and only a 500 error if something else goes wrong, for example in the transformer function.

Element API config

The defaults are set like that:

'defaults' => [
  'elementType' => Entry::class,
  'resourceKey' => 'elements',
  'pretty' => Craft::$app->getConfig()->general->devMode,   
  'paginate' => false,
  'cache' => 120
],

Additional info

TicTocLuke commented 2 years ago

We have the same issue. Rolling back to 2.8.0 resolved it. 2.8.1 is definitely where it was introduced

mihob commented 2 years ago

We have the same issue too.

angrybrad commented 2 years ago

Just pushed up a fix for this if someone wants to confirm it on their setups. https://github.com/craftcms/element-api/commit/14f465f7522bb553c57792722891386d2a6ce346

linusschwab commented 2 years ago

Thanks for the fix! With the second commit a655295 everything works again.

angrybrad commented 2 years ago

Just tagged 2.8.4 with this fix.