【问题标题】:Can I determine the response class from a superagent response?我可以从超级代理响应中确定响应类别吗?
【发布时间】:2018-04-09 03:53:11
【问题描述】:

我想在超级代理 err.status 中检查 client errors (4xx) and server errors (5xx)。来自 HTTP RFC:

状态码的第一个数字定义了响应的

我很容易写:

var _isClientOrServerError = function(errStatus){
    var errorRange = Math.floor(err.status / 100)
    return ( [5, 4].includes(errorRange) ) 
}

但是有没有更好的方法来从请求中确定响应类?

例如:

if ( res.class === 'SERVER_ERROR' )

还是类似的?

如果有插件可以做到这一点,我也很高兴。

【问题讨论】:

    标签: javascript http http-error superagent


    【解决方案1】:

    是的。 Superagent 调用 HTTP 响应类 typestatusType 字段包含响应类。来自文档:

    // status / class
    res.status = status;
    res.statusType = type;
    
    // basics
    res.info = 1 == type;
    res.ok = 2 == type;
    res.clientError = 4 == type;
    res.serverError = 5 == type;
    res.error = 4 == type || 5 == type;
    

    所以res.statusType 是包含响应类的字段(它是一个介于 1 和 5 之间的 JS Number),但检查 res.error 足以检测 4xx 或 5xx 错误。

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 2021-05-17
      • 2014-07-08
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多