1

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.",
"error_code":101
"trace": null
}

Any ideas how this is possible?

1 Answer 1

4

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
}
4
  • this will return 200 ok with error message, i want to handle using magento's exceptions
    – huzefam
    Commented May 27, 2018 at 11:27
  • ooh, I did not recognized that. I have modified the answer. Please check this may works for you. Commented May 27, 2018 at 13:46
  • oh thats interesting, will try and get back! thanks
    – huzefam
    Commented May 28, 2018 at 9:25
  • can the message in array format ?
    – jojo
    Commented Apr 14, 2020 at 1:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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