DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Updated 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.

Top comments (0)