Skip to content

Commit

Permalink
Simplified errors
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaspustina committed Jun 6, 2019
1 parent 1b1e80f commit aef956a
Show file tree
Hide file tree
Showing 7 changed files with 28 additions and 34 deletions.
2 changes: 1 addition & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl UnauthorizedClient {
let redirect_url = redirect_uri
.clone()
.into_url()
.map_err(|e| e.context(ErrorKind::HttpRequestPrepareFailed(redirect_uri.to_string())))?;
.map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest(redirect_uri.to_string())))?;

let token =
auth::authorization_code_flow(&self.client_credentials, &self.base_url, &redirect_url, code_provider)?;
Expand Down
8 changes: 4 additions & 4 deletions src/client/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fn get_code<T: CodeProvider>(
("response_type", "code"),
];
let auth_url = Url::parse_with_params(&auth_endpoint, &params)
.map_err(|e| e.context(ErrorKind::HttpRequestPrepareFailed(redirect_uri.to_string())))?;
.map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest(redirect_uri.to_string())))?;

code_provider.get_code(auth_url)
}
Expand Down Expand Up @@ -110,11 +110,11 @@ pub fn exchange_code_for_token(

if response.status() != StatusCode::OK {
let status_code = response.status();
let body = response.text().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string())))?;
let body = response.text().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;
return Err(Error::from(ErrorKind::ApiCallFailed(status_code, body)));
}

let result = response.json().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("parsing json".to_string()))?;
let result = response.json().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing json".to_string())))?;

Ok(result)
}
Expand All @@ -137,7 +137,7 @@ pub fn refresh_access_token(authorized_client: &AuthorizedClient) -> Result<Toke
.send()
.map_err(|e| e.context(ErrorKind::HttpRequestFailed))?
.json()
.map_err(|e| e.context(ErrorKind::HttpResponseReadFailed))?;
.map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing json".to_string())))?;

Ok(token)
}
2 changes: 1 addition & 1 deletion src/client/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub fn delete_documents(authorized_client: &AuthorizedClient, document_ids: &[&s

if response.status() != StatusCode::NO_CONTENT {
let status_code = response.status();
let body = response.text().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string()))?;
let body = response.text().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;
return Err(Error::from(ErrorKind::ApiCallFailed(status_code, body)));
} else {
let failed_documents = response.json::<FailedDocuments>();
Expand Down
18 changes: 9 additions & 9 deletions src/client/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ fn do_download<T: WithProgress + ?Sized>(
let mut file_path = PathBuf::from(&download.dir);
file_path.push(filename);

let file = File::create(file_path.as_path()).map_err(|e| e.context(ErrorKind::FileSystemFailure))?;
let file = File::create(file_path.as_path()).map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("creating file".to_string())))?;

let mut writer = {
if let Some(ref mut p) = progress {
Expand All @@ -109,7 +109,7 @@ fn do_download<T: WithProgress + ?Sized>(

let len = response
.copy_to(&mut writer)
.map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string()))?;
.map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;
assert_eq!(content_length, len);

if let Some(ref mut p) = writer.progress {
Expand All @@ -127,33 +127,33 @@ fn get_filename(response: &Response) -> Result<String> {
let header: Vec<_> = response
.headers()
.get(header::CONTENT_DISPOSITION)
.ok_or(ErrorKind::HttpResponseReadFailed("content disposition header".to_string())?
.ok_or(ErrorKind::FailedToProcessHttpResponse("content disposition header".to_string()))?
.as_bytes()
.to_vec();
let content_disposition: ContentDisposition =
ContentDisposition::parse_header(&[header]).map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("parsing content disposition header".to_string()))?;
ContentDisposition::parse_header(&[header]).map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing content disposition header".to_string())))?;

let mut filename = None;
for cp in &content_disposition.parameters {
if let DispositionParam::Filename(_, _, ref f) = *cp {
let decoded = str::from_utf8(f).map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("parsing content disposition filename".to_string()))?;
let decoded = str::from_utf8(f).map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing content disposition filename".to_string())))?;
filename = Some(decoded);
break;
}
}
filename
.ok_or_else(|| Error::from(ErrorKind::HttpResponseReadFailed("content disposition header filename not found".to_string()))
.ok_or_else(|| Error::from(ErrorKind::FailedToProcessHttpResponse("content disposition header filename not found".to_string())))
.map(ToString::to_string)
}

fn get_content_length(response: &Response) -> Result<u64> {
let content_length = response
.headers()
.get(header::CONTENT_LENGTH)
.ok_or(ErrorKind::HttpResponseReadFailed("content length header".to_string())?
.ok_or(ErrorKind::FailedToProcessHttpResponse("content length header".to_string()))?
.to_str()
.map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("parsing content length header".to_string()))?
.map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing content length header".to_string())))?
.parse::<u64>()
.map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("parsing content length".to_string()))?;
.map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing content length".to_string())))?;
Ok(content_length)
}
4 changes: 2 additions & 2 deletions src/client/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,11 @@ pub fn search_documents(authorized_client: &AuthorizedClient, search: Search) ->

if response.status() != StatusCode::OK {
let status_code = response.status();
let body = response.text().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string()))?;
let body = response.text().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;
return Err(Error::from(ErrorKind::ApiCallFailed(status_code, body)));
}

let result = response.json().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string()))?;
let result = response.json().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;

Ok(result)
}
Expand Down
14 changes: 7 additions & 7 deletions src/client/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ pub struct Upload<'a> {

impl<'a> Upload<'a> {
pub fn new(path: &'a Path, mime_type: Mime) -> Result<Upload<'a>> {
let metadata = path.metadata().map_err(|e| e.context(ErrorKind::FileSystemFailure))?;
let filename = path.file_name().ok_or(ErrorKind::FileSystemFailure)?.to_string_lossy();
let metadata = path.metadata().map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest("reading file metadata".to_string())))?;
let filename = path.file_name().ok_or(ErrorKind::FailedToPrepareHttpRequest("getting filename from path".to_string()))?.to_string_lossy();

Ok(Upload {
path,
Expand Down Expand Up @@ -143,11 +143,11 @@ pub fn upload_file(authorized_client: &AuthorizedClient, upload: Upload) -> Resu
* cf. https:/seanmonstar/reqwest/issues/262
*/
let mut body: Vec<u8> = Vec::new();
let nodes = create_multipart(&document_metadata, &upload).map_err(|e| e.context(ErrorKind::FailedToMultipart))?;
let nodes = create_multipart(&document_metadata, &upload).map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest("creating multipart".to_string())))?;
let boundary = generate_boundary(&upload.filename.as_bytes());
let content_type: Mime = mime!(Multipart / FormData; Boundary = (boundary));
let _ = write_multipart(&mut body, &boundary.into_bytes(), &nodes)
.map_err(|e| e.context(ErrorKind::HttpRequestPrepareFailed("multipart".to_string())))?;
.map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest("multipart".to_string())))?;

let mut response: Response = authorized_client
.http_client
Expand All @@ -164,11 +164,11 @@ pub fn upload_file(authorized_client: &AuthorizedClient, upload: Upload) -> Resu

if response.status() != StatusCode::CREATED {
let status_code = response.status();
let body = response.text().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string()))?;
let body = response.text().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;
return Err(Error::from(ErrorKind::ApiCallFailed(status_code, body)));
}

let result: Id = response.json().map_err(|e| e.context(ErrorKind::HttpResponseReadFailed("reading body".to_string()))?;
let result: Id = response.json().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;

Ok(result.id)
}
Expand All @@ -180,7 +180,7 @@ fn create_multipart(metadata: &DocumentMetadata, upload: &Upload) -> Result<Vec<
let mut nodes: Vec<Node> = Vec::with_capacity(2);

let json_bytes = serde_json::to_string(metadata)
.map_err(|e| e.context(ErrorKind::HttpRequestPrepareFailed("serializing doc-metadata json".to_string())))?
.map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest("serializing doc-metadata json".to_string())))?
.into_bytes();

let mut h = Headers::new();
Expand Down
14 changes: 4 additions & 10 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,13 @@ use std::fmt;
#[derive(Eq, PartialEq, Debug, Fail)]
pub enum ErrorKind {
#[fail(display = "failed to prepare HTTP request, '{}'", _0)]
HttpRequestPrepareFailed(String),
#[fail(display = "failed to create multipart form")]
FailedToMultipart,
FailedToPrepareHttpRequest(String),

#[fail(display = "HTTP request failed")]
HttpRequestFailed,

#[fail(display = "failed to read HTTP response, {}", _0)]
HttpResponseReadFailed(String),

#[fail(display = "filesystem failure")]
FileSystemFailure,
FailedToProcessHttpResponse(String),

#[fail(display = "API call failed with status code {}, '{}'", _0, _1)]
ApiCallFailed(StatusCode, String),
Expand All @@ -33,9 +28,8 @@ impl Clone for ErrorKind {
match *self {
HttpRequestFailed => HttpRequestFailed,
ApiCallFailed(ref status_code, ref body) => ApiCallFailed(*status_code, body.clone()),
HttpResponseReadFailed(ref s) => HttpResponseReadFailed(s.clone()),
HttpRequestPrepareFailed(ref s) => HttpRequestPrepareFailed(s.clone()),
FileSystemFailure => FileSystemFailure,
FailedToProcessHttpResponse(ref s) => FailedToProcessHttpResponse(s.clone()),
FailedToPrepareHttpRequest(ref s) => FailedToPrepareHttpRequest(s.clone()),
FailedDocuments(ref s) => FailedDocuments(s.clone()),
}
}
Expand Down

0 comments on commit aef956a

Please sign in to comment.