reconsider error and introduce custom error using thiserror

This commit is contained in:
Jun Kurihara 2022-07-27 20:09:36 +09:00
commit 6d41830eba
No known key found for this signature in database
GPG key ID: 48ADFD173ED22B03
8 changed files with 61 additions and 27 deletions

View file

@ -263,7 +263,9 @@ where
apply_upstream_options_to_header(headers, client_addr, upstream_group, &upstream_chosen.uri)?;
// update uri in request
ensure!(upstream_chosen.uri.authority().is_some() && upstream_chosen.uri.scheme().is_some());
if !(upstream_chosen.uri.authority().is_some() && upstream_chosen.uri.scheme().is_some()) {
return Err(RpxyError::Handler("Upstream uri `scheme` and `authority` is broken"));
};
let new_uri = Uri::builder()
.scheme(upstream_chosen.uri.scheme().unwrap().as_str())
.authority(upstream_chosen.uri.authority().unwrap().as_str());
@ -277,7 +279,9 @@ where
let new_pq = match &upstream_group.replace_path {
Some(new_path) => {
let matched_path: &[u8] = upstream_group.path.as_ref();
ensure!(!matched_path.is_empty() && org_pq.len() >= matched_path.len());
if matched_path.is_empty() || org_pq.len() < matched_path.len() {
return Err(RpxyError::Handler("Upstream uri `path and query` is broken"));
};
let mut new_pq = Vec::<u8>::with_capacity(org_pq.len() - matched_path.len() + new_path.len());
new_pq.extend_from_slice(new_path);
new_pq.extend_from_slice(&org_pq[matched_path.len()..]);

View file

@ -63,10 +63,9 @@ impl<B> ParseHost for Request<B> {
let uri_host = self.uri().host();
// let uri_port = self.uri().port_u16();
ensure!(
!(headers_host.is_none() && uri_host.is_none()),
"No host in request header"
);
if !(!(headers_host.is_none() && uri_host.is_none())) {
return Err(RpxyError::Request("No host in request header"));
}
// prioritize server_name in uri
uri_host.map_or_else(
@ -75,8 +74,8 @@ impl<B> ParseHost for Request<B> {
if m.starts_with(&[b'[']) {
// v6 address with bracket case. if port is specified, always it is in this case.
let mut iter = m.split(|ptr| ptr == &b'[' || ptr == &b']');
iter.next().ok_or_else(|| anyhow!("Invalid Host"))?; // first item is always blank
iter.next().ok_or_else(|| anyhow!("Invalid Host"))
iter.next().ok_or(RpxyError::Request("Invalid Host"))?; // first item is always blank
iter.next().ok_or(RpxyError::Request("Invalid Host"))
} else if m.len() - m.split(|v| v == &b':').fold(0, |acc, s| acc + s.len()) >= 2 {
// v6 address case, if 2 or more ':' is contained
Ok(m)
@ -85,7 +84,7 @@ impl<B> ParseHost for Request<B> {
m.split(|colon| colon == &b':')
.into_iter()
.next()
.ok_or_else(|| anyhow!("Invalid Host"))
.ok_or(RpxyError::Request("Invalid Host"))
}
},
|v| Ok(v.as_bytes()),