【问题标题】:JSON error response, conditional madnessJSON错误响应,有条件的疯狂
【发布时间】:2013-02-13 15:20:24
【问题描述】:

我正在制作一个request,它返回一个 JSON 正文。我已经绘制出许多不同的响应和响应中可能存在的值。我正在尝试将 JSON 吐出。

我意识到大多数 APIS 一次只吐出一个错误,但它们是另一种选择,如果您考虑表单验证中的错误消息(例如字符长度、字符、已采用),您希望所有这些错误都在一次,而且一次获得一个会很烦人。

我的问题是:是否有一种合理的更简洁的方式来委派嵌套或长 if 语句?

我可以使用条件语句的数组或对象吗?有没有一个模块可以做到这一点?

var output = {};
output.errors = [];

request(options, function(err, response, body){
    if(err){
        output.errors.push("request error ["+err.message+"]");
    }else{

        if((typeof request !== "undefined") && response && dotty.exists(response, "statusCode") && response.statusCode !== 200){
                output.errors.push("response status code "+response.statusCode);
        }

        if((typeof body !== "undefined") && body){
            if(dotty.exists(body, "countryCode") &&  dotty.exists(body, "countryName") &&  body.countryCode == "-" && body.countryName == "-"){
                output.errors.push("no country code or name present in response");
            }else if(body && dotty.exists(body, "countryCode") &&  body.countryCode == "-" &&  body.countryCode !== "" ){
                output.errors.push("no country code in response");
            }else if(body && dotty.exists(body, "countryName") && body.countryName == "-" &&  body.countryCode !== "" ){
                output.errors.push("no country name in response");
            }

            if(dotty.exists(body, "statusCode") && body.statusCode == "ERROR"){
                output.errors.push(body.statusCode);
            }

            if(dotty.exists(body, "countryCode") &&  body.countryCode !== "-" &&  body.countryCode !== "" ){
                if(!dotty.exists(output,"country")) output.country = {};
                output.country.code = body.countryCode;
            }

            if(dotty.exists(body, "countryName") &&  body.countryName !== "-" &&  body.countryCode !== "" ){
                if(!dotty.exists(output,"country")) output.country = {};
                output.country.name = body.countryName;
            }            
        }else{
            output.errors.push("no body");
        }
    }
    if(output.errors.length == 0) output.errors = false;
    res.jsonp(output);
}

这种疯狂的极限是什么?

【问题讨论】:

    标签: api node.js error-handling


    【解决方案1】:

    我选择了节点模块async,它有一个非常好的函数,叫做waterfall(),它有助于划分过程中发生的每一件事。

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 1970-01-01
      • 2011-01-28
      • 2020-11-13
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多