Skip to content

Commit 9abeea1

Browse files
authored
fix(js): throw Error on invalid header value (do not panic) (#347)
Unparseable response header values now only return `Error` in the Node bindings instead of panicking and killing the process. Related to #344
1 parent ac99829 commit 9abeea1

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

impit-node/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ impl ImpitWrapper {
149149
};
150150

151151
match response {
152-
Ok(response) => Ok(ImpitResponse::from(response)),
152+
Ok(response) => ImpitResponse::try_from_response(response),
153153
Err(err) => {
154154
let status = match err {
155155
ImpitError::UrlMissingHostnameError(_) => napi::Status::InvalidArg,

impit-node/src/response.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -77,31 +77,37 @@ impl FromNapiValue for Headers {
7777

7878
#[napi]
7979
impl<'env> ImpitResponse {
80-
pub(crate) fn from(response: Response) -> Self {
80+
pub(crate) fn try_from_response(response: Response) -> Result<Self> {
8181
let status = response.status().as_u16();
8282
let status_text = response
8383
.status()
8484
.canonical_reason()
8585
.unwrap_or("")
8686
.to_string();
87-
let headers = Headers(
88-
response
89-
.headers()
90-
.iter()
91-
.map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap().to_string()))
92-
.collect(),
93-
);
87+
let mut headers_vec: Vec<(String, String)> = Vec::new();
88+
for (k, v) in response.headers().iter() {
89+
match v.to_str() {
90+
Ok(val) => headers_vec.push((k.as_str().to_string(), val.to_string())),
91+
Err(e) => {
92+
return Err(napi::Error::new(
93+
napi::Status::GenericFailure,
94+
format!("Failed to parse header value for '{}': {:?}", k.as_str(), e),
95+
));
96+
}
97+
}
98+
}
99+
let headers = Headers(headers_vec);
94100
let ok = response.status().is_success();
95101
let url = response.url().to_string();
96102

97-
Self {
103+
Ok(Self {
98104
inner: RefCell::new(Some(response)),
99105
status,
100106
status_text,
101107
headers,
102108
ok,
103109
url,
104-
}
110+
})
105111
}
106112

107113
fn get_inner_response(&self, env: &Env, mut this: This<Object>) -> Result<Object<'_>> {

0 commit comments

Comments
 (0)