I'm working on a screen where I sent a request and I get response in two types.
One is success and contains the below format:

    "searchNames": [
            "CustomerName": "John",
            "CustomerType": "Business",
            "Profession": "Businessman",
            "address": {
                "address1": null,
                "address2": null,
                "city": null,
                "state": null,
                "country": null
            "ContactNumber": null
    "Count": 0

The other is failure response and the format differently every time, there can be no error code or message in the format.

status: "FAILURE"
error: {
errorMsg: [1]
0:  {
fieldName: "CustomerName"
errorCode: null
message: ""
errorNo: 12

I have tried validating the response and displaying the response, but I have no idea whether it is the right way to do the same.

This function is called in a promise:

console.log("result", response.searchNames );
                            var errorString = ["Error : Invalid Data"];
                              if (response.status && response.status.toLowerCase() ===
                                  'failure' && response.error && response.error.errorMsg &&
                                  response.error.errorMsg.length > 0) {
                                  var errorString = [];
                                  for (var errMsg in response.error.errorMsg) {

My questions are:

  1. Is this the right way to do the error validations, or are there any best practices for this? The error response may or may not contain error message. If there is error message, I should show the error message, otherwise I should show the default error message stored in another variable.
  2. In the success response as well is it the right way to check the success response.
    What is the right way in handling all the conditions and how can I do it?
  • 2
    \$\begingroup\$ Please format your code in a consistent manner. Also, this might be a case of where you need to report bugs to the originator of the responses and just treat every field as optional. \$\endgroup\$
    – fluffy
    Mar 8, 2015 at 17:47

1 Answer 1


The response from the server is not best practice. If you have any influence over the service, it should generate an http error (4XX range) on an exceptional condition and include the exception details in that response.

Assuming you have no control over the service, I would recommend wrapping the service call in a method returning a promise which can be resolved or rejected upon checking the response.

If you only have one piece of code making the call then I would leave it as is -- wrapping for a single call would add unnecessary complexity.


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.