0

My server checks before saving data in the database. Then if server cannot save data into database, it sends an error message.

In my client side app, how can I get this error and display it?

This is my client side http request-

button.addEventListener('click', function(e) {

            var service_ = service.value;


            if (start_pick < end_pick) {
                var jsondata = [{
                    start_time : new Date(start_pick),
                    end_time : new Date(end_pick),
                    service : service_,

                }];

                var xhr = Titanium.Network.createHTTPClient();
                xhr.setTimeout(10000);

                xhr.open("POST", "url");
                xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                xhr.send(JSON.stringify(jsondata));
                xhr.onerror = function(e) {
                     //Ti.API.debug(e.error);
                    // console.log(e.error)
                    Titanium.API.info("Error in connecting to server !!");
                    alert("Error in connecting to server !!");
                };

                xhr.onload = function(e) {
                    //alert(e)
                    if (e.error) {
                        alert(this.responseText);
                    } else  {
                        windowAddDataInvoce.close();
                }


                };

this is my server side "POST" code

app.post('/collections/:collectionName', function(req, res, next) {
   console.log(req.body[0])
  req.collection.findOne({"service":req.body[0].service}, function(e, result){
      if(result){
        console.log(result); console.log(e)
        res.send({error:"Task already exits"})
      }
      else{
        req.collection.insert(req.body, {}, function(e, results){
        if (e) return next(e)
        res.send(results)

         })
      }
  })

})

1 Answer 1

1

You have to send a correct HTTP-Status. In Express, you do this as a first argument to send, so:

res.send(500, errorMessage) or in newer Version res.status(500).body(errorMessage).

With every other status than 200, it should trigger your error-callback in the XHR-Request.

Sign up to request clarification or add additional context in comments.

1 Comment

The error message is within the body of the response. I dont know where your Titanium API puts this information - should be in the docs somewhere. Maybe as a second parameter to the error callback? But let me tell you that it is a bad pattern to send actual error messages from the server to the client - especially no stack traces or anything like that as it could reveal your servers architecture and thus make it a security threat. Define Error Messages on your client dependin the HTTP Status of the server.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.