DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Edited on

Rescript Http Error Response

Hi

Have you ever wondered how would you get Http Error Response out of the Js.Exn.t. Js.Exn.t is intentionally opaque. We need to cast to the appropriate object type. In this particular case we are trying to get Http Error response

module Response = {
  type t = {
    status: int
  }
}
@get external getResponse: Js.Exn.t => option<Response.t> = "response"
let handleError = (error: Js.Exn.t) => {
  let response = getResponse(error)
  switch response {
    | Some(response) => Js.log2("response status", response.status)
    | None => Js.log2("no response available")
  }
}

exception MyError(string)


// Now assume that we are trying to fetch 
open Promise
fetch("")
->then(todos => resolve(todos))
->catch(error => {
  handleError(error)
let err = switch e {
  | MyError(str) => "found MyError: " ++ str
  | _ => "Some unknown error"
  }

  // Here we are using the same type (`t<result>`) as in the previous `then` call
  Error(err)->resolve
})
Enter fullscreen mode Exit fullscreen mode

Hope you found it useful.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay