Browse Source

feat(core): add error message to HTTP API rejection, closes #2003 (#2004)

Lucas Fernandes Nogueira 4 years ago
parent
commit
2a5ba7fe77
3 changed files with 31 additions and 11 deletions
  1. 5 0
      .changes/http-error-message.md
  2. 3 0
      core/tauri/src/api/error.rs
  3. 23 11
      core/tauri/src/api/http.rs

+ 5 - 0
.changes/http-error-message.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch
+---
+
+Add new `Http` variant to the `tauri::api::Error` enum, including status code and error message on the HTTP API error response.

+ 3 - 0
core/tauri/src/api/error.rs

@@ -32,6 +32,9 @@ pub enum Error {
   #[cfg(feature = "reqwest-client")]
   #[error("Network Error: {0}")]
   Network(#[from] reqwest::Error),
+  /// HTTP request error. First parameter is the response status code, and the second is the response text.
+  #[error("HTTP Error: status code {0} and response `{1}`")]
+  Http(u16, String),
   /// HTTP method error.
   #[error("{0}")]
   HttpMethod(#[from] http::method::InvalidMethod),

+ 23 - 11
core/tauri/src/api/http.rs

@@ -118,12 +118,18 @@ impl Client {
       request_builder.send()?
     };
 
-    let response = response.error_for_status()?;
-    Ok(Response(
-      request.response_type.unwrap_or(ResponseType::Json),
-      response,
-      request.url,
-    ))
+    if response.is_success() {
+      Ok(Response(
+        request.response_type.unwrap_or(ResponseType::Json),
+        response,
+        request.url,
+      ))
+    } else {
+      Err(super::Error::Http(
+        response.status().as_u16(),
+        response.text()?,
+      ))
+    }
   }
 }
 
@@ -184,11 +190,17 @@ impl Client {
       request_builder.send().await?
     };
 
-    let response = response.error_for_status()?;
-    Ok(Response(
-      request.response_type.unwrap_or(ResponseType::Json),
-      response,
-    ))
+    if response.status().is_success() {
+      Ok(Response(
+        request.response_type.unwrap_or(ResponseType::Json),
+        response,
+      ))
+    } else {
+      Err(super::Error::Http(
+        response.status().as_u16(),
+        response.text().await?,
+      ))
+    }
   }
 }