Skip to content

Commit 1669c63

Browse files
committed
Revert "provide more detailed error info and align messages stylistically (#63)"
This reverts commit 3f55333. Undo the semver break for a final 0.10.x release (#71).
1 parent cc1142c commit 1669c63

File tree

6 files changed

+122
-137
lines changed

6 files changed

+122
-137
lines changed

src/clients/hyper_client.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ impl WebPushClient for HyperWebPushClient {
7171
while let Some(chunk) = chunks.data().await {
7272
body.extend(&chunk?);
7373
if body.len() > MAX_RESPONSE_SIZE {
74-
return Err(WebPushError::ResponseTooLarge);
74+
return Err(WebPushError::InvalidResponse);
7575
}
7676
}
7777
trace!("Body: {:?}", body);
@@ -82,12 +82,8 @@ impl WebPushClient for HyperWebPushClient {
8282

8383
debug!("Response: {:?}", response);
8484

85-
if let Err(WebPushError::ServerError {
86-
retry_after: None,
87-
info,
88-
}) = response
89-
{
90-
Err(WebPushError::ServerError { retry_after, info })
85+
if let Err(WebPushError::ServerError(None)) = response {
86+
Err(WebPushError::ServerError(retry_after))
9187
} else {
9288
Ok(response?)
9389
}

src/clients/isahc_client.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl WebPushClient for IsahcWebPushClient {
7575
.await?
7676
> MAX_RESPONSE_SIZE
7777
{
78-
return Err(WebPushError::ResponseTooLarge);
78+
return Err(WebPushError::InvalidResponse); // TODO: Use new error code
7979
}
8080
trace!("Body: {:?}", body);
8181

@@ -85,12 +85,8 @@ impl WebPushClient for IsahcWebPushClient {
8585

8686
trace!("Response: {:?}", response);
8787

88-
if let Err(WebPushError::ServerError {
89-
retry_after: None,
90-
info,
91-
}) = response
92-
{
93-
Err(WebPushError::ServerError { retry_after, info })
88+
if let Err(WebPushError::ServerError(None)) = response {
89+
Err(WebPushError::ServerError(retry_after))
9490
} else {
9591
Ok(response?)
9692
}

src/clients/request_builder.rs

Lines changed: 56 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,15 @@
44
use http::header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE};
55
use http::{Request, StatusCode};
66

7-
use crate::{error::ErrorInfo, error::WebPushError, message::WebPushMessage};
7+
use crate::{error::WebPushError, message::WebPushMessage};
8+
9+
#[derive(Deserialize, Serialize, Debug, PartialEq)]
10+
struct ErrorInfo {
11+
code: u16,
12+
errno: u16,
13+
error: String,
14+
message: String,
15+
}
816

917
/// Builds the request to send to the push service.
1018
///
@@ -64,28 +72,25 @@ where
6472

6573
/// Parses the response from the push service, and will return `Err` if the request was bad.
6674
pub fn parse_response(response_status: StatusCode, body: Vec<u8>) -> Result<(), WebPushError> {
67-
if response_status.is_success() {
68-
return Ok(());
69-
}
70-
71-
let info: ErrorInfo = serde_json::from_slice(&body).unwrap_or_else(|_| ErrorInfo {
72-
code: response_status.as_u16(),
73-
errno: 999,
74-
error: "unknown error".into(),
75-
message: String::from_utf8(body).unwrap_or_else(|_| "-".into()),
76-
});
77-
7875
match response_status {
79-
StatusCode::UNAUTHORIZED => Err(WebPushError::Unauthorized(info)),
80-
StatusCode::GONE => Err(WebPushError::EndpointNotValid(info)),
81-
StatusCode::NOT_FOUND => Err(WebPushError::EndpointNotFound(info)),
76+
status if status.is_success() => Ok(()),
77+
status if status.is_server_error() => Err(WebPushError::ServerError(None)),
78+
79+
StatusCode::UNAUTHORIZED => Err(WebPushError::Unauthorized),
80+
StatusCode::GONE => Err(WebPushError::EndpointNotValid),
81+
StatusCode::NOT_FOUND => Err(WebPushError::EndpointNotFound),
8282
StatusCode::PAYLOAD_TOO_LARGE => Err(WebPushError::PayloadTooLarge),
83-
StatusCode::BAD_REQUEST => Err(WebPushError::BadRequest(info)),
84-
status if status.is_server_error() => Err(WebPushError::ServerError {
85-
retry_after: None,
86-
info,
87-
}),
88-
_ => Err(WebPushError::Other(info)),
83+
84+
StatusCode::BAD_REQUEST => match String::from_utf8(body) {
85+
Err(_) => Err(WebPushError::BadRequest(None)),
86+
Ok(body_str) => match serde_json::from_str::<ErrorInfo>(&body_str) {
87+
Ok(error_info) => Err(WebPushError::BadRequest(Some(error_info.error))),
88+
Err(_) if body_str.is_empty() => Err(WebPushError::BadRequest(None)),
89+
Err(_) => Err(WebPushError::BadRequest(Some(body_str))),
90+
},
91+
},
92+
93+
e => Err(WebPushError::Other(format!("{:?}", e))),
8994
}
9095
}
9196

@@ -159,76 +164,71 @@ mod tests {
159164

160165
#[test]
161166
fn parses_a_successful_response_correctly() {
162-
assert!(matches!(parse_response(StatusCode::OK, vec![]), Ok(())));
167+
assert_eq!(Ok(()), parse_response(StatusCode::OK, vec![]))
163168
}
164169

165170
#[test]
166171
fn parses_an_unauthorized_response_correctly() {
167-
assert!(matches!(
168-
parse_response(StatusCode::UNAUTHORIZED, vec![]),
169-
Err(WebPushError::Unauthorized(_))
170-
));
172+
assert_eq!(
173+
Err(WebPushError::Unauthorized),
174+
parse_response(StatusCode::UNAUTHORIZED, vec![])
175+
)
171176
}
172177

173178
#[test]
174179
fn parses_a_gone_response_correctly() {
175-
assert!(matches!(
176-
parse_response(StatusCode::GONE, vec![]),
177-
Err(WebPushError::EndpointNotValid(_))
178-
));
180+
assert_eq!(
181+
Err(WebPushError::EndpointNotValid),
182+
parse_response(StatusCode::GONE, vec![])
183+
)
179184
}
180185

181186
#[test]
182187
fn parses_a_not_found_response_correctly() {
183-
assert!(matches!(
184-
parse_response(StatusCode::NOT_FOUND, vec![]),
185-
Err(WebPushError::EndpointNotFound(_))
186-
));
188+
assert_eq!(
189+
Err(WebPushError::EndpointNotFound),
190+
parse_response(StatusCode::NOT_FOUND, vec![])
191+
)
187192
}
188193

189194
#[test]
190195
fn parses_a_payload_too_large_response_correctly() {
191-
assert!(matches!(
192-
parse_response(StatusCode::PAYLOAD_TOO_LARGE, vec![]),
193-
Err(WebPushError::PayloadTooLarge)
194-
));
196+
assert_eq!(
197+
Err(WebPushError::PayloadTooLarge),
198+
parse_response(StatusCode::PAYLOAD_TOO_LARGE, vec![])
199+
)
195200
}
196201

197202
#[test]
198203
fn parses_a_server_error_response_correctly() {
199-
assert!(matches!(
200-
parse_response(StatusCode::INTERNAL_SERVER_ERROR, vec![]),
201-
Err(WebPushError::ServerError { .. })
202-
));
204+
assert_eq!(
205+
Err(WebPushError::ServerError(None)),
206+
parse_response(StatusCode::INTERNAL_SERVER_ERROR, vec![])
207+
)
203208
}
204209

205210
#[test]
206211
fn parses_a_bad_request_response_with_no_body_correctly() {
207-
assert!(matches!(
208-
parse_response(StatusCode::BAD_REQUEST, vec![]),
209-
Err(WebPushError::BadRequest(_))
210-
));
212+
assert_eq!(
213+
Err(WebPushError::BadRequest(None)),
214+
parse_response(StatusCode::BAD_REQUEST, vec![])
215+
)
211216
}
212217

213218
#[test]
214219
fn parses_a_bad_request_response_with_body_correctly() {
215220
let json = r#"
216221
{
217-
"code": 400,
222+
"code": 404,
218223
"errno": 103,
219224
"error": "FooBar",
220225
"message": "No message found"
221226
}
222227
"#;
223228

224-
assert!(matches!(
225-
parse_response(StatusCode::BAD_REQUEST, json.as_bytes().to_vec()),
226-
Err(WebPushError::BadRequest(ErrorInfo {
227-
code: 400,
228-
errno: 103,
229-
error: _,
230-
message: _,
231-
})),
232-
));
229+
assert_eq!(
230+
Err(WebPushError::BadRequest(Some(String::from("FooBar")))),
231+
parse_response(StatusCode::BAD_REQUEST, json.as_bytes().to_vec())
232+
)
233233
}
234234
}

src/error.rs

Lines changed: 58 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -6,49 +6,32 @@ use base64::DecodeError;
66
use http::uri::InvalidUri;
77
use serde_json::error::Error as JsonError;
88

9-
#[derive(Debug, Clone, Serialize, Deserialize)]
10-
pub struct ErrorInfo {
11-
pub code: u16,
12-
pub errno: u16,
13-
pub error: String,
14-
pub message: String,
15-
}
16-
17-
impl fmt::Display for ErrorInfo {
18-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19-
write!(
20-
f,
21-
"code {}, errno {}: {} ({})",
22-
self.code, self.errno, self.error, self.message
23-
)
24-
}
25-
}
26-
27-
#[derive(Debug)]
9+
#[derive(PartialEq, Debug, Clone, Ord, PartialOrd, Eq, Deserialize, Serialize, Hash)]
2810
pub enum WebPushError {
29-
/// An unknown error happened while encrypting or sending the message
11+
/// An unknown error happened encrypting the message,
3012
Unspecified,
3113
/// Please provide valid credentials to send the notification
32-
Unauthorized(ErrorInfo),
14+
Unauthorized,
3315
/// Request was badly formed
34-
BadRequest(ErrorInfo),
16+
BadRequest(Option<String>),
3517
/// Contains an optional `Duration`, until the user can retry the request
36-
ServerError {
37-
retry_after: Option<Duration>,
38-
info: ErrorInfo,
39-
},
18+
ServerError(Option<Duration>),
4019
/// The feature is not implemented yet
41-
NotImplemented(ErrorInfo),
20+
NotImplemented,
4221
/// The provided URI is invalid
4322
InvalidUri,
4423
/// The URL specified is no longer valid and should no longer be used
45-
EndpointNotValid(ErrorInfo),
24+
EndpointNotValid,
4625
/// The URL specified is invalid and should not be used again
47-
EndpointNotFound(ErrorInfo),
26+
EndpointNotFound,
4827
/// Maximum allowed payload size is 3800 characters
4928
PayloadTooLarge,
29+
/// Could not initialize a TLS connection
30+
TlsError,
31+
/// Error in SSL signing
32+
SslError,
5033
/// Error in reading a file
51-
Io(IoError),
34+
IoError,
5235
/// Make sure the message was addressed to a registration token whose
5336
/// package name matches the value passed in the request (Google).
5437
InvalidPackageName,
@@ -64,9 +47,7 @@ pub enum WebPushError {
6447
InvalidResponse,
6548
/// A claim had invalid data
6649
InvalidClaims,
67-
/// Response from push endpoint was too large
68-
ResponseTooLarge,
69-
Other(ErrorInfo),
50+
Other(String),
7051
}
7152

7253
impl Error for WebPushError {}
@@ -104,8 +85,8 @@ impl From<isahc::Error> for WebPushError {
10485
}
10586

10687
impl From<IoError> for WebPushError {
107-
fn from(err: IoError) -> WebPushError {
108-
WebPushError::Io(err)
88+
fn from(_: IoError) -> WebPushError {
89+
WebPushError::IoError
10990
}
11091
}
11192

@@ -119,53 +100,65 @@ impl WebPushError {
119100
pub fn short_description(&self) -> &'static str {
120101
match *self {
121102
WebPushError::Unspecified => "unspecified",
122-
WebPushError::Unauthorized(_) => "unauthorized",
103+
WebPushError::Unauthorized => "unauthorized",
123104
WebPushError::BadRequest(_) => "bad_request",
124-
WebPushError::ServerError { .. } => "server_error",
125-
WebPushError::NotImplemented(_) => "not_implemented",
105+
WebPushError::ServerError(_) => "server_error",
106+
WebPushError::NotImplemented => "not_implemented",
126107
WebPushError::InvalidUri => "invalid_uri",
127-
WebPushError::EndpointNotValid(_) => "endpoint_not_valid",
128-
WebPushError::EndpointNotFound(_) => "endpoint_not_found",
108+
WebPushError::EndpointNotValid => "endpoint_not_valid",
109+
WebPushError::EndpointNotFound => "endpoint_not_found",
129110
WebPushError::PayloadTooLarge => "payload_too_large",
111+
WebPushError::TlsError => "tls_error",
130112
WebPushError::InvalidPackageName => "invalid_package_name",
131113
WebPushError::InvalidTtl => "invalid_ttl",
132114
WebPushError::InvalidTopic => "invalid_topic",
133115
WebPushError::InvalidResponse => "invalid_response",
134116
WebPushError::MissingCryptoKeys => "missing_crypto_keys",
135117
WebPushError::InvalidCryptoKeys => "invalid_crypto_keys",
136-
WebPushError::Io(_) => "io_error",
118+
WebPushError::SslError => "ssl_error",
119+
WebPushError::IoError => "io_error",
137120
WebPushError::Other(_) => "other",
138121
WebPushError::InvalidClaims => "invalidClaims",
139-
WebPushError::ResponseTooLarge => "response_too_large",
140122
}
141123
}
142124
}
143125

144126
impl fmt::Display for WebPushError {
145127
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
146-
match self {
147-
WebPushError::Unspecified => write!(f, "unspecified error"),
148-
WebPushError::Unauthorized(info) => write!(f, "unauthorized: {}", info),
149-
WebPushError::BadRequest(info) => write!(f, "bad request: {}", info),
150-
WebPushError::ServerError { info, .. } => write!(f, "server error: {}", info),
151-
WebPushError::PayloadTooLarge => write!(f, "maximum payload size of 3070 characters exceeded"),
152-
WebPushError::InvalidUri => write!(f, "invalid uri provided"),
153-
WebPushError::NotImplemented(info) => write!(f, "not implemented: {}", info),
154-
WebPushError::EndpointNotValid(info) => write!(f, "endpoint not valid: {}", info),
155-
WebPushError::EndpointNotFound(info) => write!(f, "endpoint not found: {}", info),
156-
WebPushError::Io(err) => write!(f, "i/o error: {}", err),
157-
WebPushError::InvalidPackageName => write!(
158-
f,
159-
"package name of registration token does not match package name provided in the request"
160-
),
161-
WebPushError::InvalidTtl => write!(f, "invalid or missing ttl value"),
162-
WebPushError::InvalidTopic => write!(f, "invalid topic value"),
163-
WebPushError::InvalidResponse => write!(f, "could not parse response data"),
164-
WebPushError::MissingCryptoKeys => write!(f, "request is missing cryptographic keys"),
165-
WebPushError::InvalidCryptoKeys => write!(f, "request has invalid cryptographic keys"),
166-
WebPushError::Other(info) => write!(f, "other: {}", info),
167-
WebPushError::InvalidClaims => write!(f, "at least one jwt claim was invalid"),
168-
WebPushError::ResponseTooLarge => write!(f, "response from push endpoint was too large"),
128+
match *self {
129+
WebPushError::Unspecified =>
130+
write!(f, "An unknown error happened encrypting the message"),
131+
WebPushError::Unauthorized =>
132+
write!(f, "Please provide valid credentials to send the notification"),
133+
WebPushError::BadRequest(_) =>
134+
write!(f, "Request was badly formed"),
135+
WebPushError::ServerError(_) =>
136+
write!(f, "Server was unable to process the request, please try again later"),
137+
WebPushError::PayloadTooLarge =>
138+
write!(f, "Maximum allowed payload size is 3070 characters"),
139+
WebPushError::InvalidUri =>
140+
write!(f, "The provided URI is invalid"),
141+
WebPushError::NotImplemented =>
142+
write!(f, "The feature is not implemented yet"),
143+
WebPushError::EndpointNotValid =>
144+
write!(f, "The URL specified is no longer valid and should no longer be used"),
145+
WebPushError::EndpointNotFound =>
146+
write!(f, "The URL specified is invalid and should not be used again"),
147+
WebPushError::TlsError =>
148+
write!(f, "Could not initialize a TLS connection"),
149+
WebPushError::SslError =>
150+
write!(f, "Error signing with SSL"),
151+
WebPushError::IoError =>
152+
write!(f, "Error opening a file"),
153+
WebPushError::InvalidPackageName =>
154+
write!(f, "Make sure the message was addressed to a registration token whose package name matches the value passed in the request."),
155+
WebPushError::InvalidTtl => write!(f, "The TTL value provided was not valid or was not provided"),
156+
WebPushError::InvalidTopic => write!(f, "The Topic value provided was invalid"),
157+
WebPushError::InvalidResponse => write!(f, "The response data couldn't be parses"),
158+
WebPushError::MissingCryptoKeys => write!(f, "The request is missing cryptographic keys"),
159+
WebPushError::InvalidCryptoKeys => write!(f, "The request is having invalid cryptographic keys"),
160+
WebPushError::Other(_) => write!(f, "An unknown error when connecting the notification service"),
161+
WebPushError::InvalidClaims => write!(f, "At least one JWT claim was invalid.")
169162
}
170163
}
171164
}

0 commit comments

Comments
 (0)