我在对象内部使用异步函数在 express.js 中发送响应
Controller 代码:
module.exports = {
async signUpEmail(req, res) {
/**
* @description Parameters from body
* @param {string} firstName - First Name
* @inner
*/
const firstName = req.body.firstName;
res.send({ success: name });
throw new Error(); // purposely Done
}
}
问题:
因为 signUpEmail 方法在我的例子中是异步的,无论我的异步方法在这里抛出什么,它都会被拒绝,所以它出现了 Error。(故意放在那里)
因此将其记录在控制台中。
(node:13537) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error
(node:13537) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
所以我应该从调用它的路由中处理它。
路由器代码
const routes = require('express').Router();
const SignUpController = require('../controllers/signUpController')
// /signup
routes.post('/', SignUpController.signUpEmail);
module.exports = routes;
像这样的 SignUpController.signUpEmail().then(…); 但是因为我没有在路由中调用函数,所以我只是传递。 如何有效地做到这一点?
PS:请不要提出过于复杂的解决方案。我是 JS 的初学者,正在学习。
我没有使用可链接的路由处理程序,因为我想创建模块化的、可安装的路由处理程序。
最佳答案
在你的路由中,你需要添加一个包装器来捕获抛出的错误:
let wrapper = fn => (...args) => fn(...args).catch(args[2]);
// /signup
routes.post('/', wrapper(SignUpController.signUpEmail));
通过这种方法,您可以使用顶级错误捕获器,而不需要在您的路由中使用内部 try catch block ,除非您根据上下文需要它们。
使用错误捕获中间件实现如下:
// last middleware in chain
app.use(function(err, req, res, next) {
// handle your errors
});
现在在你的路由中你可以抛出错误,它们会被那个中间件捕获。我喜欢在这个中间件中抛出自定义错误并处理它们的响应和日志记录。
旁白:async await 模式非常适合编写易于人们以同步方式阅读的异步代码。请记住,一旦你开始异步,你就应该保持异步!强烈建议使用 Bluebird 等 promisification 库并在 nodeback 库上调用 .promisifyAll。
编辑:Source - Asynchronous Error Handling in Express with Promises, Generators and ES7
关于javascript - 如何处理 Node.js expressjs 中异步对象方法中未处理的 promise 拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43564222/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案