简体   繁体   中英

Error handling node.js

I'm trying to learn node.js

I've got a working function and trying to handle an exeption like this:

Client.Session.create(device, storage, username, password)
    .then(function(session) {
        session.getAccount()
          .then(function(account) {
           console.log(account.params)
           res.statusCode = 200
           res.setHeader('Content-Type', 'application/json')
           res.end(JSON.stringify(account.params));  
           return session   
    })
    }).catch(Exceptions.AuthenticationError, function(err) {
            console.log(err)
        })

but it isn't working I'm still getting this in case of invalid login:

Unhandled rejection AuthenticationError: The username you entered doesn't appear to belong to an account. Please check your username and try again.

Try

Client.Session.create(device, storage, username, password)
    .then(function(session) {
        return session.getAccount() <-- NOTICE THE RETURN STATEMENT!!
          .then(function(account) {
           console.log(account.params)
           res.statusCode = 200
           res.setHeader('Content-Type', 'application/json')
           res.end(JSON.stringify(account.params));
           return session
        })
    }).catch(Exceptions.AuthenticationError, function(err) {
            console.log(err)
    })

Without the return, the .then handler of the promise returned by Client.Session.Create(...) will return a resolved promise (this is its default behaviour).

Promise rejections aren't any kind of exceiptions, so they aren't automatically rethrown as it would be if you were added, for example, something like this:

session.getAccount(...).then(...).catch(function(){throw "FooBar"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM