Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala.js.dom ajax.post, error when error status

Tags:

scala.js

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?

like image 231
ndesmoul Avatar asked Dec 14 '22 10:12

ndesmoul


1 Answers

This is expected. Ajax.post returns a Future, and the map method of Futures 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 Futures, 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
}
like image 107
sjrd Avatar answered Feb 12 '23 14:02

sjrd