javascriptrestmvvmpromisecanjs

How to handle can-connect errors correcly when connecting to a RESTful API


I've managed to load data and to save data. But cannot understand the error handling scheme needed. When everything goes fine I receive the same object in that was sent but with an extra attribute _saving (false).

When something goes wrong, for instance try to store a string instead of a number, I'll get:

  1. Bad request (error on the console, don't want that)
  2. The response object (might be usefull to show an error)
  3. "Uncaught (in promise)" error

Example:

Code:
this.save()
    .then(function(result) {
    console.log('ok1', result);
}).catch(function() {
    console.log('errorHandler1');
});

I've been trying to use catch on promises, following this guidelines: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch but had no luck at all.

This should should work buy just changing p1.then to thisObjectThatIWantToSave.save.then but it didn't.

p1.then(function(value) {
    console.log(value); // "Success!"
    throw 'oh, no!';
}).catch(function(e) {
    console.log(e); // "oh, no!"
}).then(function(){
    console.log('after a catch the chain is restored');
}, function () {
    console.log('Not fired due to the catch');
});

Again, it still stores the information when the data is correct, the problem I see is that I don't have the tools to decide when was the data correctly stored or not and to avoid triggering errors that can be correctly handled.

I'm using


Solution

  • Regarding the error handling ...

    Bad request (error on the console, don't want that)

    There's no way of preventing the error on the console. This is something chrome does.

    The response object (might be usefull to show an error)

    You can read the reason for the rejection in can-stache like {{promise.reason}}.

    "Uncaught (in promise)" error

    I'm not sure why this is being thrown as clearly, your catch is being hit. If you change it to:

    this.save()
        .then(function(result) {
        console.log('ok1', result);
    },function() {
        console.log('errorHandler1');
    });
    

    Do you get the same behavior?