我使用scala.js(0.6.5)和scala-js-dom(0.8.2)并且我有一些带有ajax.post的奇怪的pb,当我收到错误状态(这里是409).
浏览器控制台显示错误消息,但是从我的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}")
}
})
Run Code Online (Sandbox Code Playgroud)
状态为201时,效果很好.
在我的情况下,当我发送的数据已经存在时,我应该得到一个409错误代码,带有一些消息状态.从浏览器调试工具来看确实如此.
我希望能够在执行'request.map'时管理错误情况,但是当返回错误代码时,不会执行此代码.
那么如何用POST消息管理错误呢?
sjr*_*jrd 10
这是预料之中的.Ajax.post返回a Future,s 的map方法Future仅针对成功案例执行.返回码409被视为失败,因此将以失败状态完成未来.
要使用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)
})
Run Code Online (Sandbox Code Playgroud)
如果您希望在与成功返回代码相同的代码中处理失败返回代码,则可以先将 recover失败AjaxException(req)转为成功req:
request.recover {
// Recover from a failed error code into a successful future
case dom.ext.AjaxException(req) => req
}.map(req => {
// handle all status codes
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
987 次 |
| 最近记录: |