Add HTTP error handling to CLI example

This commit is contained in:
Richard Feldman 2021-04-06 22:45:04 -04:00
parent dba526bb3e
commit a3c7dc494b
4 changed files with 17 additions and 17 deletions

View file

@ -9,8 +9,8 @@ main =
url <- await Stdin.line
{} <- await (Stdout.line "The contents of \(url) are:\n")
result <- Task.attempt (Http.getUtf8 url)
contents <- await (Http.getUtf8 url)
Stdout.line contents
when result is
Ok contents -> Stdout.line "The contents of \(url) are:\n\(contents)"
Err err -> Stdout.line "Error retrieving \(url) - error was: \(err)"

View file

@ -2,5 +2,5 @@ interface Http
exposes [ getUtf8 ]
imports [ fx.Effect, Task ] # TODO FIXME Task.{ Task }
getUtf8 : Str -> Task.Task Str *
getUtf8 = \url -> Effect.map (Effect.httpGetUtf8 url) Ok
getUtf8 : Str -> Task.Task Str Str
getUtf8 = \url -> Effect.httpGetUtf8 url

View file

@ -8,7 +8,7 @@ platform rtfeldman/roc-cli
{
putChar : I64 -> Effect {},
putLine : Str -> Effect {},
httpGetUtf8 : Str -> Effect Str,
httpGetUtf8 : Str -> Effect (Result Str Str),
getLine : Effect Str
}

View file

@ -45,16 +45,16 @@ pub fn roc_fx_putLine(line: RocStr) -> () {
}
#[no_mangle]
pub fn roc_fx_httpGetUtf8(url: RocStr) -> RocStr {
let body = ureq::get(unsafe { url.as_str() })
.call()
.unwrap_or_else(|err| todo!("Report this HTTP error: {:?}", err));
let str = body
.into_string()
.unwrap_or_else(|err| todo!("Report this body.text() error: {:?}", err));
RocStr::from_slice(str.as_bytes())
pub fn roc_fx_httpGetUtf8(url: RocStr) -> RocResult<RocStr, RocStr> {
match ureq::get(unsafe { url.as_str() }).call() {
Ok(resp) => match resp.into_string() {
Ok(contents) => RocResult::Ok(RocStr::from_slice(contents.as_bytes())), // TODO make roc::Result!
// TODO turn this error into an enum!
Err(err) => RocResult::Err(RocStr::from_slice(format!("{:?}", err).as_bytes())),
},
// TODO turn this error into an enum!
Err(err) => RocResult::Err(RocStr::from_slice(format!("{:?}", err).as_bytes())),
}
}
#[no_mangle]