-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Use thiserror for credential provider errors #12424
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5321146
Add serde(default) to cargo-credential RegistryInfo headers
arlosi a81d558
Use thiserror for credential provider errors
arlosi 7918c7f
Remove from impls
arlosi 70b584e
Add serde(other) to credential protocol enums for future proofing
arlosi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,206 @@ | ||
use serde::{Deserialize, Serialize}; | ||
use std::error::Error as StdError; | ||
use thiserror::Error as ThisError; | ||
|
||
/// Credential provider error type. | ||
/// | ||
/// `UrlNotSupported` and `NotFound` errors both cause Cargo | ||
/// to attempt another provider, if one is available. The other | ||
/// variants are fatal. | ||
/// | ||
/// Note: Do not add a tuple variant, as it cannot be serialized. | ||
#[derive(Serialize, Deserialize, ThisError, Debug)] | ||
#[serde(rename_all = "kebab-case", tag = "kind")] | ||
#[non_exhaustive] | ||
pub enum Error { | ||
epage marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// Registry URL is not supported. This should be used if | ||
/// the provider only works for some registries. Cargo will | ||
/// try another provider, if available | ||
#[error("registry not supported")] | ||
UrlNotSupported, | ||
|
||
/// Credentials could not be found. Cargo will try another | ||
/// provider, if available | ||
#[error("credential not found")] | ||
NotFound, | ||
|
||
/// The provider doesn't support this operation, such as | ||
/// a provider that can't support 'login' / 'logout' | ||
#[error("requested operation not supported")] | ||
OperationNotSupported, | ||
|
||
/// The provider failed to perform the operation. Other | ||
/// providers will not be attempted | ||
#[error(transparent)] | ||
#[serde(with = "error_serialize")] | ||
Other(Box<dyn StdError + Sync + Send>), | ||
|
||
/// A new variant was added to this enum since Cargo was built | ||
#[error("unknown error kind; try updating Cargo?")] | ||
#[serde(other)] | ||
Unknown, | ||
} | ||
|
||
impl From<String> for Error { | ||
fn from(err: String) -> Self { | ||
Box::new(StringTypedError { | ||
message: err.to_string(), | ||
source: None, | ||
}) | ||
.into() | ||
} | ||
} | ||
|
||
impl From<&str> for Error { | ||
fn from(err: &str) -> Self { | ||
err.to_string().into() | ||
} | ||
} | ||
|
||
impl From<anyhow::Error> for Error { | ||
fn from(value: anyhow::Error) -> Self { | ||
let mut prev = None; | ||
for e in value.chain().rev() { | ||
prev = Some(Box::new(StringTypedError { | ||
message: e.to_string(), | ||
source: prev, | ||
})); | ||
} | ||
Error::Other(prev.unwrap()) | ||
} | ||
} | ||
|
||
impl<T: StdError + Send + Sync + 'static> From<Box<T>> for Error { | ||
fn from(value: Box<T>) -> Self { | ||
Error::Other(value) | ||
} | ||
} | ||
|
||
/// String-based error type with an optional source | ||
#[derive(Debug)] | ||
struct StringTypedError { | ||
message: String, | ||
source: Option<Box<StringTypedError>>, | ||
} | ||
|
||
impl StdError for StringTypedError { | ||
fn source(&self) -> Option<&(dyn StdError + 'static)> { | ||
self.source.as_ref().map(|err| err as &dyn StdError) | ||
} | ||
} | ||
|
||
impl std::fmt::Display for StringTypedError { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
self.message.fmt(f) | ||
} | ||
} | ||
|
||
/// Serializer / deserializer for any boxed error. | ||
/// The string representation of the error, and its `source` chain can roundtrip across | ||
/// the serialization. The actual types are lost (downcast will not work). | ||
mod error_serialize { | ||
use std::error::Error as StdError; | ||
use std::ops::Deref; | ||
|
||
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serializer}; | ||
|
||
use crate::error::StringTypedError; | ||
|
||
pub fn serialize<S>( | ||
e: &Box<dyn StdError + Send + Sync>, | ||
serializer: S, | ||
) -> Result<S::Ok, S::Error> | ||
where | ||
S: Serializer, | ||
{ | ||
let mut state = serializer.serialize_struct("StringTypedError", 2)?; | ||
state.serialize_field("message", &format!("{}", e))?; | ||
|
||
// Serialize the source error chain recursively | ||
let mut current_source: &dyn StdError = e.deref(); | ||
let mut sources = Vec::new(); | ||
while let Some(err) = current_source.source() { | ||
sources.push(err.to_string()); | ||
current_source = err; | ||
} | ||
state.serialize_field("caused-by", &sources)?; | ||
state.end() | ||
} | ||
|
||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Box<dyn StdError + Sync + Send>, D::Error> | ||
where | ||
D: Deserializer<'de>, | ||
{ | ||
#[derive(Deserialize)] | ||
#[serde(rename_all = "kebab-case")] | ||
struct ErrorData { | ||
message: String, | ||
caused_by: Option<Vec<String>>, | ||
} | ||
let data = ErrorData::deserialize(deserializer)?; | ||
let mut prev = None; | ||
if let Some(source) = data.caused_by { | ||
for e in source.into_iter().rev() { | ||
prev = Some(Box::new(StringTypedError { | ||
message: e, | ||
source: prev, | ||
})); | ||
} | ||
} | ||
let e = Box::new(StringTypedError { | ||
message: data.message, | ||
source: prev, | ||
}); | ||
Ok(e) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::Error; | ||
|
||
#[test] | ||
pub fn unknown_kind() { | ||
let json = r#"{ | ||
"kind": "unexpected-kind", | ||
"unexpected-content": "test" | ||
}"#; | ||
let e: Error = serde_json::from_str(&json).unwrap(); | ||
assert!(matches!(e, Error::Unknown)); | ||
} | ||
Comment on lines
+162
to
+170
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: was this meant to be part of the next commit? |
||
|
||
#[test] | ||
pub fn roundtrip() { | ||
// Construct an error with context | ||
let e = anyhow::anyhow!("E1").context("E2").context("E3"); | ||
// Convert to a string with contexts. | ||
let s1 = format!("{:?}", e); | ||
// Convert the error into an `Error` | ||
let e: Error = e.into(); | ||
// Convert that error into JSON | ||
let json = serde_json::to_string_pretty(&e).unwrap(); | ||
// Convert that error back to anyhow | ||
let e: anyhow::Error = e.into(); | ||
let s2 = format!("{:?}", e); | ||
assert_eq!(s1, s2); | ||
|
||
// Convert the error back from JSON | ||
let e: Error = serde_json::from_str(&json).unwrap(); | ||
// Convert to back to anyhow | ||
let e: anyhow::Error = e.into(); | ||
let s3 = format!("{:?}", e); | ||
assert_eq!(s2, s3); | ||
|
||
assert_eq!( | ||
r#"{ | ||
"kind": "other", | ||
"message": "E3", | ||
"caused-by": [ | ||
"E2", | ||
"E1" | ||
] | ||
}"#, | ||
json | ||
); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.