Question

So let's say I have a model, responding to my webapi calls, whats the best way to return an error to the api consumer. For example, in the code below, the second line query the category factory (di-ed) for a specific category id, if not found, the function natively throws \Magento\Framework\Exception\NoSuchEntityException and the webapi will return 404 as below. This is all good, but should I as a best practice:

  • Just leave the exception thrown by the factory as below (might not be the best option, since I don't want to expose the trace to api consumers)
  • Catch it and throw the same exception type without the trace
  • Catch it and throw a webapi exception throw new \Magento\Framework\Webapi\Exception ( __("Category not found"), \Magento\Framework\Webapi\Exception::HTTP_NOT_FOUND)

/**
 * @param int $id
 * @return array
 */
public function getById( $id ){

    $store_id = $this->request->getParam('store_id');
    $category = $this->category_repo->get($id, $store_id);

{
  "message": "No such entity with %fieldName = %fieldValue",
  "parameters": {
    "fieldName": "id",
    "fieldValue": 13
  },
  "trace": "#0 C:\\stage\\appfactory-magento2\\vendor\\magento\\module-catalog\\Model\\CategoryRepository.php(141): Magento\\Framework\\Exception\\NoSuchEntityException::singleField('id', 13)\n#1 C:\\stage\\appfactory-magento2\\app\\code\\AppFactory\\Basic\\Model\\Api\\Category.php(59): Magento\\Catalog\\Model\\CategoryRepository->get(13, NULL)\n#2 [internal function]: AppFactory\\Basic\\Model\\Api\\Category->getById(13)\n#3 C:\\stage\\appfactory-magento2\\vendor\\magento\\module-webapi\\Controller\\Rest.php(307): call_user_func_array(Array, Array)\n#4 C:\\stage\\appfactory-magento2\\vendor\\magento\\module-webapi\\Controller\\Rest.php(216): Magento\\Webapi\\Controller\\Rest->processApiRequest()\n#5 C:\\stage\\appfactory-magento2\\var\\generation\\Magento\\Webapi\\Controller\\Rest\\Interceptor.php(37): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#6 C:\\stage\\appfactory-magento2\\vendor\\magento\\framework\\App\\Http.php(135): Magento\\Webapi\\Controller\\Rest\\Interceptor->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#7 C:\\stage\\appfactory-magento2\\vendor\\magento\\framework\\App\\Bootstrap.php(258): Magento\\Framework\\App\\Http->launch()\n#8 C:\\stage\\appfactory-magento2\\index.php(39): Magento\\Framework\\App\\Bootstrap->run(Object(Magento\\Framework\\App\\Http))\n#9 {main}"
}

In Magento 1.x, I used to do it like this:

if (!($category->getId())) $this->_critical(self::RESOURCE_NOT_FOUND);
Was it helpful?

Solution

For the most of cases I think you could leave the exception thrown. Trace option doesn't show in production mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top