Javascript 使用Node.js、Async和Node.js处理错误
在下面的代码片段中,我想验证第一个异步方法中的字段 如果它们无效,我想立即向用户返回一个错误 我该怎么做Javascript 使用Node.js、Async和Node.js处理错误,javascript,node.js,async.js,formidable,Javascript,Node.js,Async.js,Formidable,在下面的代码片段中,我想验证第一个异步方法中的字段 如果它们无效,我想立即向用户返回一个错误 我该怎么做 var form = new formidable.IncomingForm(); async1.series([ function (callback) { form.parse(req); form.on('field', function (name, val) { // Get the fields
var form = new formidable.IncomingForm();
async1.series([
function (callback) {
form.parse(req);
form.on('field', function (name, val) {
// Get the fields
});
form.on('fileBegin', function (name, file) {
if (file.name !== "") {
file.path = __dirname + '/upload/' + file.name;
}
});
callback();
},
function (callback) {
form.on('file', function (name, file) {
try {
// Do something with the file using the fields retrieved from first async method
}
catch (err) {
logger.info(err);
}
});
callback();
}
], function (err) {
//the upload failed, there is nothing we can do, send a 500
if (err === "uploadFailed") {
return res.send(500);
}
if (err) {
throw err;
}
return res.status(200);
});
我假设这是一个验证的好地方,因为这是字段进入的时候:
form.on('field', function (name, val) {
//if values are null
if (!name || !val) {
//pass the callback an error
return callback("Values are null")
}
// Get the fields
});
如果有帮助,请告诉我。
var form=new.IncomingForm();
异步1.0系列([
函数(回调){
form.parse(req);
表单.on('field',函数(name,val){
如果(!name | |!val){
//调用回调时出错,async将停止执行任何步骤
//并执行作为最后一个参数提供的函数
//idimoatic节点,当调用带有错误实例的回调时
返回回调(新错误('InvalidParams');
}
/**
*这来自异步文档:https://caolan.github.io/async/docs.html#series
*依次运行tasks集合中的函数,每个函数运行一次上一个函数
*已完成。如果该系列中的任何函数向其回调传递错误,则不会再调用其他函数
*运行,则立即使用错误值调用回调。否则,回调将接收
*任务完成时的结果数组。
*/
});
表单.on('fileBegin',函数(名称,文件){
如果(file.name!==“”){
file.path=\uu dirname+'/upload/'+file.name;
}
});
表单.on('end',函数(){
//使用null调用callback以指定没有错误
//如果有一些结果,则像回调一样调用它(null,results);
返回回调(null);
});
//如果在注册on('field')等的事件处理程序后立即调用回调,
//没有时间触发这些事件,到那时,此功能将被禁用
//执行完毕。
//回调();
},
函数(回调){
表单.on('file',函数(名称,文件){
试一试{
//使用从第一个异步方法检索的字段对文件执行某些操作
}
捕捉(错误){
logger.info(err);
返回回调(err);
}
});
//这也不应该立即调用
//回调();
}
],函数(err){
//上传失败,我们无能为力,发送500
如果(错误==“上传失败”){
返回res.send(500);
}
如果(err.message=='InvalidParams'){
//这将立即返回给用户。
返回res.sendStatus(400);
}
如果(错误){
//我不确定这是否只是一个示例,但如果不是,就不应该抛出错误
//在运行时。
犯错误;
}
返回res.status(200);
});代码>我将把表单检查提取到函数中:
var form = new formidable.IncomingForm();
function check(name, cb, err) {
return new Promise((res,rej) => {
form.on('field', function(n, val) {
if(n !== name) return;
if(cb(val)){
res(val);
}else{
rej(err);
}
});
});
}
form.parse(req);
因此,现在我们可以实施检查,并使用Promise.all对其进行总结:
Promise.all(
check("username", val => val.length > 4, "username isnt valid"),
check("password", val => true, "we need a password")
).then(_ => res.json({status:200}))
.catch(err => res.json({err}));
如果不是所有参数都已传递,这将无休止地等待。因此,如果它已结束,则让我们终止:
const ended = new Promise((_,rej) => form.on("end", () => rej("params required"));
Promise.race(
ended,
Promise.all(
check("username", val => val.length > 4, "username isnt valid"),
check("password", val => true, "we need a password")
)
).then(_ => res.json({status:200}))
.catch(err => res.json({err}));
因此,我们可以创建良好的数据流。e、 g:
const login = Promise.all(
//usable as one liners
check("username", val => val.length >= 8, "username invalid"),
//or more extensible
check("password", val => {
if( val.length < 8 ) return false;
//other checks
console.log(password);
return true;
}, "password invalid")
//the field values are resolved by the promises so we can summarize them below
).then(([username,password]) =>
//a random (maybe async) call to evaluate the credentials
checkAgainstDB(username,password)
//we can directly fail here, err is "password invalid" or "username invalid"
).catch(err => res.json({error:"login failed",details:err}));
//another parameter can be extra handled
const data = check("something", val => val.length);
//we need to summarize all the possible paths (login /data in this case) to one that generates the result
Promise.race(
//here we join them together
Promise.all(login, data)
.then((l, d) => res.json(whatever),
//and we use the ended promise ( from above ) to end the whole thing
ended
//and at last the errors that can occur if the response ended or that have not been canceled early
).catch(e => res.json(e));
const login=Promise.all(
//可用作一行程序
选中(“用户名”,val=>val.length>=8,“用户名无效”),
//或更可扩展
检查(“密码”,val=>{
如果(val.length<8)返回false;
//其他支票
console.log(密码);
返回true;
},“密码无效”)
//字段值由承诺解析,因此我们可以在下面对其进行总结
)。然后(([用户名,密码])=>
//用于评估凭据的随机(可能是异步)调用
checkAgainstDB(用户名、密码)
//我们可以直接在这里失败,错误为“密码无效”或“用户名无效”
).catch(err=>res.json({error:“登录失败”,详细信息:err}));
//另一个参数可以额外处理
常量数据=检查(“某物”,val=>val.length);
//我们需要将所有可能的路径(本例中的登录/数据)汇总为生成结果的路径
承诺,种族(
//在这里,我们把他们连在一起
Promise.all(登录、数据)
.然后((l,d)=>res.json(无论什么),
//我们用结束的承诺(从上面)来结束整件事
结束了
//以及如果响应结束或未提前取消,可能发生的错误
).catch(e=>res.json(e));
错误被抛出到哪里?有没有办法将错误返回到API调用?在我的代码中,我相信它会通过error参数发送到异步系列中的最后一个函数。要将其发送到API调用(我假设类似于Express),也许可以执行“return res.send”(“值为null”)这将导致在返回错误时回调()已被调用。形式为.on('end')的回调将抛出error@Robben_Ford_Fan_boy明白了!我现在更好地理解了这个问题并更新了我的答案。请检查编辑并让我知道这是否有帮助。您可以返回带有错误的回调返回回调(err)
立即从检查字段的if块开始,该回调将直接执行发送响应代码的回调处理程序函数
。