ZijianHe / koa-router

Router middleware for koa.
MIT License
4.85k stars 407 forks source link

Promises chain and catch errors #370

Open lesterzone opened 7 years ago

lesterzone commented 7 years ago

First: Thank you, this is an amazing effort and a great package.

Second: I'm pretty sure I'm missing something, I'm learning and getting async/await into my head. Working with promises since AFAIK I can't use another approach within current project.

Third:

Using koa@2.3.0, koa-router@7.2 and https://github.com/koajs/koa/wiki/Error-Handling#catching-downstream-errors

function middleware(context, next) {
  return apromise()
    .then(data => doSomething(data))
    .then(data => context.body = data)
    .catch(next); // I'd love to use this approach so _global_ error handler takes care of errors
}
router.get('/stars', middleware);

.catch is not 'working' to pass errors, the expected behavior will be:

function middleware(context, next) {
  return new Promise((resolve, reject) => {
    return apromise()
      .then(data => doSomething(data))
      .then(data => context.body = data)
      .catch(reject); // now the error is properly handled by _global_ handler
  });
}

Thank you.

jbielick commented 7 years ago

What is "global error handler"?

jbielick commented 7 years ago

I recommend you ask this question on Stack Overflow. This section of github is for issues with the library and tracking bugs. You will likely find more help with your goal on a forum like Stack Overflow.

YanLobat commented 7 years ago

@jbielick Hi! Can you check #244?

YanLobat commented 7 years ago

@lesterzone I had a look on your issue, and at least I can say that next is a Promise(you can check it in koa documentation) and this is not correct use Example of using promises:

const promise = new Promise((resolve, reject) => 
  if (smth) {
    resolve('success');
  }
  else {
    reject('err');
  }
);
promise
.then(result => {
  console.log(result);//We got here from resolve callback
})
.catch(err => {
  console.log(err); // Here we go from reject callack
});

In context of koa people use await next(); it allows go downstream to next middlewares