From 2456bc1b28daa0042187c88c101e8f7917360bfd Mon Sep 17 00:00:00 2001 From: Andrew Lamb Date: Fri, 12 Mar 2021 09:30:45 -0500 Subject: [PATCH] refactor: impl Error for FieldViolation (#975) --- generated_types/src/google.rs | 14 +++++++++++++- src/commands/database/chunk.rs | 8 ++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/generated_types/src/google.rs b/generated_types/src/google.rs index 51339d87bc..75b204397e 100644 --- a/generated_types/src/google.rs +++ b/generated_types/src/google.rs @@ -84,6 +84,18 @@ impl FieldViolation { } } +impl std::error::Error for FieldViolation {} + +impl std::fmt::Display for FieldViolation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Violation for field \"{}\": {}", + self.field, self.description + ) + } +} + fn encode_bad_request(violation: Vec) -> Result { let mut buffer = BytesMut::new(); @@ -106,7 +118,7 @@ fn encode_bad_request(violation: Vec) -> Result for tonic::Status { fn from(f: FieldViolation) -> Self { - let message = format!("Violation for field \"{}\": {}", f.field, f.description); + let message = f.to_string(); match encode_bad_request(vec![f]) { Ok(details) => encode_status(tonic::Code::InvalidArgument, message, details), diff --git a/src/commands/database/chunk.rs b/src/commands/database/chunk.rs index 6f8c3a3806..b5ab4cf70c 100644 --- a/src/commands/database/chunk.rs +++ b/src/commands/database/chunk.rs @@ -14,8 +14,8 @@ pub enum Error { #[error("Error listing chunks: {0}")] ListChunkError(#[from] ListChunksError), - #[error("Error interpreting server response: {:?}", .0)] - ConvertingResponse(FieldViolation), + #[error("Error interpreting server response: {0}")] + ConvertingResponse(#[from] FieldViolation), #[error("Error rendering response as JSON: {0}")] WritingJson(#[from] serde_json::Error), @@ -62,8 +62,8 @@ pub async fn command(url: String, config: Config) -> Result<()> { let chunks = chunks .into_iter() - .map(|c| ChunkSummary::try_from(c).map_err(Error::ConvertingResponse)) - .collect::>>()?; + .map(ChunkSummary::try_from) + .collect::, FieldViolation>>()?; serde_json::to_writer_pretty(std::io::stdout(), &chunks).map_err(Error::WritingJson)?; }