Rescript Http Error Response
Srikanth Kyatham

Srikanth Kyatham @srikanthkyatham

About: Software engineer interested in building stuff

Location:
Oulu, Finland
Joined:
Jun 21, 2020

Rescript Http Error Response

Publish Date: Aug 12 '23
0 0

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.

Comments 0 total

    Add comment