scala-js / scala-js-dom

Statically typed DOM API for Scala.js
Other
315 stars 160 forks source link

Recommended approach when `Response.type` is undefined? #755

Closed greg-a-atkinson closed 1 year ago

greg-a-atkinson commented 1 year ago

Hi!

I was wondering what is the best approach to dealing with Response.`type` when the underlying js.native value is undefined?

/** [[https://fetch.spec.whatwg.org/#response ¶6.4 Response class]] in whatwg spec
  * ...
  */
@js.native
@JSGlobal
class Response(content: BodyInit = null, init: ResponseInit = null) extends Body {

  /** Contains the type of the response */
  def `type`: ResponseType = js.native

When this is case the following error is raised:

org.scalajs.linker.runtime.UndefinedBehaviorError: java.lang.ClassCastException: undefined cannot be cast to java.lang.String

ResponseType does not currently support this scenario:

/** see [[https://fetch.spec.whatwg.org/#responsetype]] of whatwg Fetch spec */
object ResponseType {
  val basic: ResponseType = "basic"
  val cors: ResponseType = "cors"
  val default: ResponseType = "default"
  val error: ResponseType = "error"
  val opaque: ResponseType = "opaque"
  val opaqueredirect: ResponseType = "opaqueredirect"
}

Unfortunately I don't control nor can I alter the server returning the response with an empty content type, to what is originally a POST request.

The best I have for now is to wrap the call to Response.`type` in either a very forgiving try-catch statement:

val respTypeOpt = try Some(resp.`type`) catch case _: Throwable => None

Or a deeper specific try-catch statement:

val respTypeOpt =
  try Some(resp.`type`)
  catch
    case t: Throwable =>
      t.getCause() match
        case _: ClassCastException => None
        case _ => throw t

Any ideas?

Thank you!

sjrd commented 1 year ago

Hello,

This looks like a question on using Scala.js, rather than a bug report. The GitHub Issues in this repo are for bug reports and feature requests only. Please ask questions on StackOverflow or on Discord (channel #scala-js), where more than just the core developers can see and answer.

Thank you for your understanding.


That said, for anyone reading this and thinking about the try/catch solution, it's not going to work in fullLinkJS because it relies on undefined behavior.