我正在尝试为自定义错误实现一个模块。
应该可以使用此模块在应用程序的要求声明中实例化单个错误:
var MyCustomError = require('custom-error')('MyCustomError');
这是模块:
'use strict';
var _CACHE = {};
function initError(name) {
function CustomError(message) {
this.name = name;
this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
_CACHE[name] = CustomError;
}
function createCustomError(name) {
if (!_CACHE[name]) {
initError(name);
}
return _CACHE[name];
}
module.exports = createCustomError;
到目前为止,上面的 require-one-liner 正在运行。
现在,在我的服务中,我想明确地捕获这个错误:
var MyCustomError = require('custom-error')('MyCustomError')
// ...
return fooService.bar()
.catch(MyCustomError, function (error) {
logger.warn(error);
throw error;
})
如果我在我的测试中通过抛出 MyCustomError 来拒绝 fooService.bar 的 promise ,这很好。
但是,这只有效,因为我的测试和服务正在使用 MyCustomError 的相同实例。
例如,如果我删除自定义错误模块中的缓存机制,则不会再到达/执行 catch,因为 bluebird 不明白这两个错误属于同一类型:
function createCustomError(name) {
//if (!_CACHE[name]) {
initError(name);
//}
return _CACHE[name];
}
bluebird处理的具体代码在catch_filter.js中,可以看看right here .
虽然该方法在我的应用程序中确实有效,但一旦多个模块使用自定义错误模块并且不再共享相同实例,这很快就会导致问题。
如何通过不比较实例,而是比较错误类型本身来启动和运行这个概念?
干杯,
克里斯托弗
最佳答案
我终于想出了一个稍微不同的方法。对于志同道合的人来说,这是结果:
错误工厂
var
vsprintf = require("sprintf-js").vsprintf;
function CustomErrorFactory(code, name, httpCode, message) {
// Bluebird catcher
this.predicate = function (it) {
return it.code === code;
};
this.new = function (messageParameters, details) {
return new CustomError(messageParameters, details);
};
this.throw = function (messageParameters, details) {
throw new CustomError(messageParameters, details);
};
function CustomError(messageParameters, details) {
this.code = code;
this.name = name;
this.message = vsprintf(message, messageParameters);
this.httpCode = httpCode;
this.details = details || {};
// Important: Do not swallow the stacktrace that lead to here.
// @See http://stackoverflow.com/questions/8802845/inheriting-from-the-error-object-where-is-the-message-property
Error.captureStackTrace(this, CustomError);
}
// CustomError must be instance of the Error-Object
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
}
module.exports = CustomErrorFactory;
错误
var
ErrorFactory = require("./ErrorFactory");
function initErrors() {
return {
Parameter: {
Missing: new ErrorFactory('1x100', 'ParameterMissing', 400, 'Parameter "%s" missing'),
Invalid: new ErrorFactory('1x200', 'ParameterInvalid', 400, 'Parameter "%s" invalid')
//..
},
Access: {
NotAccessible: new ErrorFactory('3x100', 'AccessNotAccessible', 403, 'Resource "%s" is not accessible for "%s"'),
//..
},
// ...
Request: {
//..
}
};
}
module.exports = initErrors();
我创建了一个包含这些类的单独模块。
然后,在我的实现中,我可以单独捕获这样的错误:
function foo(request, reply) {
return bluebird
.resolve(bar)
.then(reply)
.catch(Errors.Parameter.Missing.predicate, function () {
return reply(boom.badRequest());
})
.catch(Errors.Entity.NotFound.predicate, function () {
return reply({}).code(204);
})
.catch(Errors.Entity.IllegalState.predicate, function (error) {
return reply(boom.badImplementation(error.message));
})
// any other error
.catch(function (error) {
return reply(boom.badImplementation(error.message));
});
}
throw
Errors.Entity.IllegalState.throw(['foo', 'bar']);
// or
throw Errors.Entity.IllegalState.new(['foo', 'bar']);
要求
Errors = require('errors'); // all
EntityErors = require('errors').Entity; // one group
EntityNotFoundError = require('errors').Entity.NotFound; // one particular
唯一我仍然不明白的是为什么需要使用谓词函数而不是仅仅将错误对象传递给 catch 子句。但我可以忍受。
关于javascript - 自定义错误和 bluebird 的 catch with ErrorClass 导致无意行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33814737/
我正在尝试设置一个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
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>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
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin