简体   繁体   English

Promise解决何时应捕获错误

[英]Promise resolves when it should be catching error

I have a simple node+express app that makes a few async http/get url requests if you visit a certain page. 我有一个简单的node + express应用程序,如果您访问某个页面,它会发出一些异步http / get url请求。 This is to simply get some data from the db, and send that to the view. 这是简单地从数据库中获取一些数据,并将其发送到视图。 The routes are handled using a standard separate routes.js file. 使用标准的单独的routes.js文件处理路由。

routes.js

...
const bluebird = require('bluebird');
const promiseRequest = bluebird.promisify(require('request'));

Promise.all([
  promiseRequest(`http://url1...`),
  promiseRequest(`http://url2...`)
])
.then((promiseRes) => {
  res.render(...); // loads the view for the client
})
.catch((err) => {
  errorHandler(err, req, res); // to be handled by express middleware
});

The http url requests are handled using a controller file, which makes a query to the db, and returns either the values or an error. 使用控制器文件处理http url请求,该文件向db进行查询,并返回值或错误。

controller.js

try {
  const {rows, rowCount} = await db.query(findAllQuery);
  return res.status(200).send({rows, rowCount});
} catch (error) {
  return res.status(400).send({
    "name": error.name,
    "psql_error_code": error.code
  });
}

The controller is working fine, but I am purposely typing in a wrong get url so that the controller returns the res.status(400)... object back to the route. 控制器工作正常,但我故意输入了错误的get url,以便控制器将res.status(400)...对象返回到路由。 No matter what I return to the route, the promise resolves. 无论我返回什么路线,诺言都会解决。 I even tried returning a new Error('Error description') , but the promisify receives this as a resolution. 我什至尝试返回一个new Error('Error description') ,但是promisify将此作为解决方法。

Any help would be deeply appreciated! 任何帮助将不胜感激!

-- -

The response from the controller to the route is a lengthy object . 控制器对路线的响应是一个漫长的对象

As I can not see how you have implemented errorHandler(). 如我所见,您是如何实现errorHandler()的。 One thing I can think of that you should look for is that - if inside .catch(err){} of the called promise you are not returning any error, it will go to the then of the calling function. 我可以想到的一件事是,您应该寻找的是-如果在被调用的promise的.catch(err){}内没有返回任何错误,它将转到调用函数的then。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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