Skip to content

Commit

Permalink
feat: improve server function client side error handling (#1597)
Browse files Browse the repository at this point in the history
Handle all error codes 401-499 in addition to the
400 and 500-599 that were already handled.

In addition, handle them all in the same way
and improve the error message.
  • Loading branch information
drdo authored Aug 30, 2023
1 parent 700eee6 commit 4d7e1f4
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions server_fn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,14 +555,22 @@ where
let status = resp.status();
#[cfg(not(target_arch = "wasm32"))]
let status = status.as_u16();
if (500..=599).contains(&status) {
if (400..=599).contains(&status) {
let text = resp.text().await.unwrap_or_default();
#[cfg(target_arch = "wasm32")]
let status_text = resp.status_text();
#[cfg(not(target_arch = "wasm32"))]
let status_text = status.to_string();
return Err(serde_json::from_str(&text)
.unwrap_or(ServerFnError::ServerError(status_text)));
return Err(match serde_json::from_str(&text) {
Ok(e) => e,
Err(_) => {
#[cfg(target_arch = "wasm32")]
let status_text = resp.status_text();
#[cfg(not(target_arch = "wasm32"))]
let status_text = status.to_string();
ServerFnError::ServerError(if text.is_empty() {
format!("{} {}", status, status_text)
} else {
format!("{} {}: {}", status, status_text, text)
})
}
});
}

// Decoding the body of the request
Expand All @@ -582,12 +590,6 @@ where
#[cfg(not(target_arch = "wasm32"))]
let binary = binary.as_ref();

if status == 400 {
return Err(ServerFnError::ServerError(
"No server function was found at this URL.".to_string(),
));
}

ciborium::de::from_reader(binary)
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
} else {
Expand All @@ -596,10 +598,6 @@ where
.await
.map_err(|e| ServerFnError::Deserialization(e.to_string()))?;

if status == 400 {
return Err(ServerFnError::ServerError(text));
}

let mut deserializer = JSONDeserializer::from_str(&text);
T::deserialize(&mut deserializer)
.map_err(|e| ServerFnError::Deserialization(e.to_string()))
Expand Down

0 comments on commit 4d7e1f4

Please sign in to comment.