In Magento2, while returning an error from a rest endpoint, i can throw an exception like this

throw new \Magento\Framework\Webapi\Exception(__('No centers matching search criteria'))

It will throw an error like

enter image description here

My requirement, is to add an error code along with response i.e.

"message": "No centers matching search criteria.",
"trace": null

Any ideas how this is possible?


You have to pass error code as a 2nd parameter as given below:

throw new \Magento\Framework\Webapi\Exception(__('No centers matching search criteria'),101)

Then the response should be looks like as:

"message": "No centers matching search criteria.",
"code": 101,
"trace": null
  • this will return 200 ok with error message, i want to handle using magento's exceptions – huzefam May 27 '18 at 11:27
  • ooh, I did not recognized that. I have modified the answer. Please check this may works for you. – Prasanta Hatui May 27 '18 at 13:46
  • oh thats interesting, will try and get back! thanks – huzefam May 28 '18 at 9:25
  • can the message in array format ? – jojo Apr 14 '20 at 1:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.