Skip to content

Commit 3a6695e

Browse files
authored
replace unwrap calls in azure_core (#661)
1 parent 966061c commit 3a6695e

File tree

8 files changed

+46
-29
lines changed

8 files changed

+46
-29
lines changed

sdk/core/src/context.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ impl Context {
3232
// the `unwrap` below is safe.
3333
self.type_map
3434
.insert(TypeId::of::<E>(), Arc::new(entity))
35-
.map(|displaced| displaced.downcast().unwrap())
35+
.map(|displaced| displaced.downcast().expect("failed to unwrap downcast"))
3636
}
3737

3838
/// Inserts an entity in the type map. If the an entity with the same type signature is
@@ -54,7 +54,7 @@ impl Context {
5454
{
5555
self.type_map
5656
.remove(&TypeId::of::<E>())
57-
.map(|removed| removed.downcast().unwrap())
57+
.map(|removed| removed.downcast().expect("failed to unwrap downcast"))
5858
}
5959

6060
/// Returns a reference of the entity of the specified type signature, if it exists.

sdk/core/src/error/azure_core_errors.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ impl From<crate::errors::HttpError> for Error {
3636
crate::HttpError::Utf8(e) => Error::new(ErrorKind::DataConversion, e),
3737
crate::HttpError::BuildResponse(e) => Error::new(ErrorKind::DataConversion, e),
3838
crate::HttpError::BuildClientRequest(e) => Error::new(ErrorKind::Other, e),
39+
crate::HttpError::Url(e) => Error::new(ErrorKind::Other, e),
3940
}
4041
}
4142
}

sdk/core/src/error/http_error.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::Response;
2+
use std::collections::HashMap;
23

34
/// An unsuccessful HTTP response
45
#[derive(Debug)]
@@ -16,13 +17,13 @@ impl HttpError {
1617
pub async fn new(response: Response) -> Self {
1718
let status = response.status();
1819
let mut error_code = get_error_code_from_header(&response);
19-
let headers = response
20-
.headers()
21-
.into_iter()
22-
// TODO: the following will panic if a non-UTF8 header value is sent back
23-
// We should not panic but instead handle this gracefully
24-
.map(|(n, v)| (n.as_str().to_owned(), v.to_str().unwrap().to_owned()))
25-
.collect();
20+
let mut headers = HashMap::new();
21+
22+
for (name, value) in response.headers() {
23+
let value = String::from_utf8_lossy(value.as_bytes()).to_string();
24+
headers.insert(name.to_string(), value);
25+
}
26+
2627
let body = response.into_body_string().await;
2728
error_code = error_code.or_else(|| get_error_code_from_body(&body));
2829
HttpError {

sdk/core/src/errors.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ pub enum HttpError {
133133
BuildResponse(#[source] http::Error),
134134
#[error("failed to reset stream")]
135135
StreamReset(#[source] StreamError),
136+
#[error("failed to parse URL")]
137+
Url(#[from] url::ParseError),
136138
}
137139

138140
/// An error caused by invalid permissions.

sdk/core/src/http_client.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,8 @@ pub trait HttpClient: Send + Sync + std::fmt::Debug {
108108
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
109109
impl HttpClient for reqwest::Client {
110110
async fn execute_request(&self, request: Request<Bytes>) -> Result<Response<Bytes>, HttpError> {
111-
let mut reqwest_request = self.request(
112-
request.method().clone(),
113-
url::Url::parse(&request.uri().to_string()).unwrap(),
114-
);
111+
let url = url::Url::parse(&request.uri().to_string())?;
112+
let mut reqwest_request = self.request(request.method().clone(), url);
115113
for (header, value) in request.headers() {
116114
reqwest_request = reqwest_request.header(header, value);
117115
}
@@ -149,10 +147,8 @@ impl HttpClient for reqwest::Client {
149147
&self,
150148
request: &crate::Request,
151149
) -> Result<crate::Response, HttpError> {
152-
let mut reqwest_request = self.request(
153-
request.method(),
154-
url::Url::parse(&request.uri().to_string()).unwrap(),
155-
);
150+
let url = url::Url::parse(&request.uri().to_string())?;
151+
let mut reqwest_request = self.request(request.method(), url);
156152
for header in request.headers() {
157153
reqwest_request = reqwest_request.header(header.0, header.1);
158154
}

sdk/core/src/policies/retry_policies/retry_policy.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,18 @@ where
6161
}
6262
Ok(response) => {
6363
// Error status code
64-
let error = HttpError::new(response).await;
65-
let status = StatusCode::from_u16(error.status()).unwrap();
64+
let code = response.status().as_u16();
65+
66+
let http_error = HttpError::new(response).await;
67+
// status code should already be parsed as valid from the underlying HTTP
68+
// implementations.
69+
let status = StatusCode::from_u16(code).expect("invalid status code");
6670
let error = Error::full(
6771
ErrorKind::http_response(
68-
status.as_u16(),
69-
error.error_code().map(|s| s.to_owned()),
72+
code,
73+
http_error.error_code().map(|s| s.to_owned()),
7074
),
71-
error,
75+
http_error,
7276
"server returned error status which will not be retried",
7377
);
7478

sdk/core/src/request_options/content_range.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,14 @@ impl FromStr for ContentRange {
4949
})?;
5050

5151
let mut split_at_dash = remaining.split('-');
52-
let start = split_at_dash.next().unwrap().parse()?;
52+
let start = split_at_dash
53+
.next()
54+
.ok_or_else(|| ParseError::TokenNotFound {
55+
item: "ContentRange",
56+
token: "-".to_owned(),
57+
full: s.into(),
58+
})?
59+
.parse()?;
5360

5461
let mut split_at_slash = split_at_dash
5562
.next()
@@ -60,7 +67,15 @@ impl FromStr for ContentRange {
6067
})?
6168
.split('/');
6269

63-
let end = split_at_slash.next().unwrap().parse()?;
70+
let end = split_at_slash
71+
.next()
72+
.ok_or_else(|| ParseError::TokenNotFound {
73+
item: "ContentRange",
74+
token: "/".to_owned(),
75+
full: s.into(),
76+
})?
77+
.parse()?;
78+
6479
let total_length = split_at_slash
6580
.next()
6681
.ok_or_else(|| ParseError::TokenNotFound {

sdk/core/src/request_options/metadata.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,10 @@ impl From<&HeaderMap> for Metadata {
7878
header_map
7979
.iter()
8080
.map(|header| (header.0.as_str(), header.1.as_bytes()))
81-
.filter(|(key, _)| key.starts_with("x-ms-meta-"))
8281
.for_each(|(key, value)| {
83-
metadata.insert(
84-
key.strip_prefix("x-ms-meta-").unwrap().to_owned(),
85-
value.to_owned(),
86-
);
82+
if let Some(key) = key.strip_prefix("x-ms-meta-") {
83+
metadata.insert(key.to_owned(), value.to_owned());
84+
}
8785
});
8886

8987
metadata

0 commit comments

Comments
 (0)