Magento 2 REST API – Handling 400 Bad Request Error Codes

magento2rest api

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?

Best Answer

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
}