【问题标题】:scala.js.dom ajax.post, error when error statusscala.js.dom ajax.post,错误状态时出错
【发布时间】:2016-02-28 14:08:00
【问题描述】:

我使用 scala.js (0.6.5) 和 scala-js-dom (0.8.2),当我收到错误状态(此处为 409)时,我有一些带有 ajax.post 的奇怪 pb。
浏览器控制台显示一条错误消息,但从我的 scala 代码中,我无法访问状态代码和返回的消息。

这是我用于发送 POST 的代码:

val request = Ajax.post(
  url,
  data = postData,
  headers = bsHeaders)

request.map(xhr => {
  log.debug("response text: " + xhr.responseText)

  if (xhr.status == 201) {
    try {
      val loc = xhr.getResponseHeader("Location")
      if(loc == locHeaderResp) {
        loc
      } else {
        log.error(s"Location header invalid: ${loc}")
      }
    } catch {
      case e:Exception => {
        log.error("Couldn't read 'Location' header " + e.getMessage)
        log.debug("List of headers: " + xhr.getAllResponseHeaders())
        ""
      }
    }
  } else if (xhr.status == 409) {
    log.error("" + xhr.responseText)
    log.error(s"${xhr.responseText}")
  } else {
    log.error(s"Request failed with response code ${xhr.status}")
    log.error(s"${xhr.responseText}")
  }
})

当状态为201时,效果很好。

在我的情况下,当我发送的数据已经存在时,我应该得到一个 409 错误代码,以及一些消息状态。而从浏览器调试工具来看确实如此。

我希望在执行“request.map”时能够管理错误情况,但是当返回错误代码时,此代码不会执行。

那么如何管理 POST 消息的错误呢?

【问题讨论】:

    标签: scala.js


    【解决方案1】:

    这是意料之中的。 Ajax.post 返回一个Future,而Futures 的map 方法只在成功 的情况下执行。返回码 409 被视为失败,因此将以 failed 状态完成未来。

    要使用Futures 处理失败,您应该使用他们的onFailure 方法:

    request.map(req => {
      // ... handle success cases (req.status is 2xx or 304)
    }).onFailure {
      case dom.ext.AjaxException(req) =>
        // ... handle failure cases (other return codes)
    })
    

    如果您希望在与成功返回码相同的代码中处理失败返回码,您可以首先 recover 将失败的AjaxException(req) 变成成功的req: p>

    request.recover {
      // Recover from a failed error code into a successful future
      case dom.ext.AjaxException(req) => req
    }.map(req => {
      // handle all status codes
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 2021-05-20
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多