I a using scala.js (0.6.5) and scala-js-dom (0.8.2) and I have some strange pb with an ajax.post, when I receive an error status (409 here).
The browser console shows an error message, but from my scala code I cannot have access to the status code, and to the message returned.
Here is the code I use for sending a 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}")
}
})
When the status is 201, it works well.
In my case, when the data I am sending already exists, I am supposed to get a 409 error code, with some message status. And from the browser debugging tools it is indeed the case.
I was expecting to be able to manage error case when doing the 'request.map', but when an error code is returned, this code is not executed.
So how to manage errors with POST messages?
This is expected. Ajax.post
returns a Future
, and the map
method of Future
s are only executed for the successful cases. A return code of 409 is considered a failure, and will therefore complete the future with a failed status.
To handle failures with Future
s, you should use their onFailure
method:
request.map(req => {
// ... handle success cases (req.status is 2xx or 304)
}).onFailure {
case dom.ext.AjaxException(req) =>
// ... handle failure cases (other return codes)
})
If you would rather deal with failure return codes in the same code as success return codes, you can first recover
to turn a failed AjaxException(req)
into a successful 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With