A Magento mug with coffee spilled

Handle Magento SOAP API Errors

There are two kinds of errors from Magento: server errors like HTTP 500 status code and API errors like “Session expired. Try to relogin.”. There are also (de)serialization errors that could occur if Java model does not match with response. Let’s take a look at them.

Server Errors

It’s easy to catch server errors because they fall into failure method of Callback. RetrofitError contains HTTP status code, headers and body which describe the problem. It’s usually 500 Internal Server Error when you e.g. kill staging server with too many requests for list of all products ;)

  

API Errors

If API can’t handle your request, then error response is returned instead of expected successful message. So output class should contain not only valid response fields but also error fields. It’s required because Magento SOAP API returns errors with HTTP 200 status code and Retrofit can’t catch them in Callback.failure (and this is expected from most SOAP APIs). Note that we use @Path annotation to indicate where error fields are located in XML structure.

  

Now we can catch errors in Callback.success method.

  

(De)serialization

If server response contains more fields than you defined in model, you should set strict = false in @Root annotation. If some element is not returned in every request, you should set required = false. Otherwise you can get SimpleXml deserialization exception because some XML elements doesn’t have their Java equivalent fields and vice versa. It’s called Loose object mapping and it’s worth to set up for safety (e.g. in case of API response change). The LoginResponse class in one of above snippets is defined that way.

I would like to write something about downloading products list and how to filter them. Enjoyed these posts about Magento and Android? Share this post and give us a feedback :)