Skip to content

Commit 52fdcc7

Browse files
committed
Use anyhow for error handling
1 parent 1839720 commit 52fdcc7

File tree

12 files changed

+56
-128
lines changed

12 files changed

+56
-128
lines changed

Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ rustdoc-args = [
2828
]
2929

3030
[dependencies]
31+
anyhow = "1.0"
3132
cargo-registry-s3 = { path = "src/s3", version = "0.2.0" }
3233
rand = "0.7"
3334
git2 = "0.13.0"

src/bin/enqueue-job.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
#![deny(clippy::all)]
22

3-
use cargo_registry::{db, env, tasks, util::Error};
3+
use anyhow::{anyhow, Result};
4+
use cargo_registry::{db, env, tasks};
45
use diesel::prelude::*;
56
use swirl::schema::background_jobs::dsl::*;
67
use swirl::Job;
78

8-
fn main() -> Result<(), Error> {
9+
fn main() -> Result<()> {
910
let conn = db::connect_now()?;
1011
let mut args = std::env::args().skip(1);
1112

@@ -34,6 +35,6 @@ fn main() -> Result<(), Error> {
3435
.unwrap_or_else(|| String::from("db-dump.tar.gz"));
3536
Ok(tasks::dump_db(database_url, target_name).enqueue(&conn)?)
3637
}
37-
other => Err(Error::from(format!("Unrecognized job type `{}`", other))),
38+
other => Err(anyhow!("Unrecognized job type `{}`", other)),
3839
}
3940
}

src/bin/monitor.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88

99
mod on_call;
1010

11-
use cargo_registry::{db, schema::*, util::Error};
11+
use anyhow::Result;
12+
use cargo_registry::{db, schema::*};
1213
use diesel::prelude::*;
1314

14-
fn main() -> Result<(), Error> {
15+
fn main() -> Result<()> {
1516
let conn = db::connect_now()?;
1617

1718
check_failing_background_jobs(&conn)?;
@@ -28,7 +29,7 @@ fn main() -> Result<(), Error> {
2829
///
2930
/// Within the default 15 minute time, a job should have already had several
3031
/// failed retry attempts.
31-
fn check_failing_background_jobs(conn: &PgConnection) -> Result<(), Error> {
32+
fn check_failing_background_jobs(conn: &PgConnection) -> Result<()> {
3233
use cargo_registry::schema::background_jobs::dsl::*;
3334
use diesel::dsl::*;
3435
use diesel::sql_types::Integer;
@@ -70,7 +71,7 @@ fn check_failing_background_jobs(conn: &PgConnection) -> Result<(), Error> {
7071
}
7172

7273
/// Check for an `update_downloads` job that has run longer than expected
73-
fn check_stalled_update_downloads(conn: &PgConnection) -> Result<(), Error> {
74+
fn check_stalled_update_downloads(conn: &PgConnection) -> Result<()> {
7475
use cargo_registry::schema::background_jobs::dsl::*;
7576
use chrono::{DateTime, NaiveDateTime, Utc};
7677

@@ -107,7 +108,7 @@ fn check_stalled_update_downloads(conn: &PgConnection) -> Result<(), Error> {
107108
}
108109

109110
/// Check for known spam patterns
110-
fn check_spam_attack(conn: &PgConnection) -> Result<(), Error> {
111+
fn check_spam_attack(conn: &PgConnection) -> Result<()> {
111112
use cargo_registry::models::krate::canon_crate_name;
112113
use diesel::dsl::*;
113114
use diesel::sql_types::Bool;
@@ -168,7 +169,7 @@ fn check_spam_attack(conn: &PgConnection) -> Result<(), Error> {
168169
Ok(())
169170
}
170171

171-
fn log_and_trigger_event(event: on_call::Event) -> Result<(), Error> {
172+
fn log_and_trigger_event(event: on_call::Event) -> Result<()> {
172173
match event {
173174
on_call::Event::Trigger {
174175
ref description, ..

src/bin/on_call/mod.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
use cargo_registry::util::Error;
2-
1+
use anyhow::{anyhow, Result};
32
use reqwest::{blocking::Client, header, StatusCode as Status};
43

54
#[derive(serde::Serialize, Debug)]
@@ -25,7 +24,7 @@ impl Event {
2524
///
2625
/// If the variant is `Trigger`, this will page whoever is on call
2726
/// (potentially waking them up at 3 AM).
28-
pub fn send(self) -> Result<(), Error> {
27+
pub fn send(self) -> Result<()> {
2928
let api_token = dotenv::var("PAGERDUTY_API_TOKEN")?;
3029
let service_key = dotenv::var("PAGERDUTY_INTEGRATION_KEY")?;
3130

@@ -43,15 +42,15 @@ impl Event {
4342
s if s.is_success() => Ok(()),
4443
Status::BAD_REQUEST => {
4544
let error = response.json::<InvalidEvent>()?;
46-
Err(format!("pagerduty error: {:?}", error))
45+
Err(anyhow!("pagerduty error: {:?}", error))
4746
}
48-
Status::FORBIDDEN => Err("rate limited by pagerduty".to_string()),
49-
n => Err(format!(
47+
Status::FORBIDDEN => Err(anyhow!("rate limited by pagerduty")),
48+
n => Err(anyhow!(
5049
"Got a non 200 response code from pagerduty: {} with {:?}",
51-
n, response
50+
n,
51+
response
5252
)),
5353
}
54-
.map_err(Into::into)
5554
}
5655
}
5756

src/bin/test-pagerduty.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ mod on_call;
1111

1212
use std::env::args;
1313

14-
use cargo_registry::util::Error;
14+
use anyhow::Result;
1515

16-
fn main() -> Result<(), Error> {
16+
fn main() -> Result<()> {
1717
let args = args().collect::<Vec<_>>();
1818

1919
let event_type = &*args[1];

src/boot/categories.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
// Sync available crate categories from `src/categories.toml`.
22
// Runs when the server is started.
33

4-
use crate::{db, util::Error};
4+
use crate::db;
55

6+
use anyhow::{Context, Result};
67
use diesel::prelude::*;
78

89
#[derive(Debug)]
@@ -34,16 +35,10 @@ impl Category {
3435
}
3536
}
3637

37-
fn required_string_from_toml<'a>(
38-
toml: &'a toml::value::Table,
39-
key: &str,
40-
) -> Result<&'a str, Error> {
41-
toml.get(key).and_then(toml::Value::as_str).ok_or_else(|| {
42-
Error::from(format!(
43-
"Expected category TOML attribute '{}' to be a String",
44-
key
45-
))
46-
})
38+
fn required_string_from_toml<'a>(toml: &'a toml::value::Table, key: &str) -> Result<&'a str> {
39+
toml.get(key)
40+
.and_then(toml::Value::as_str)
41+
.with_context(|| format!("Expected category TOML attribute '{}' to be a String", key))
4742
}
4843

4944
fn optional_string_from_toml<'a>(toml: &'a toml::value::Table, key: &str) -> &'a str {
@@ -53,13 +48,13 @@ fn optional_string_from_toml<'a>(toml: &'a toml::value::Table, key: &str) -> &'a
5348
fn categories_from_toml(
5449
categories: &toml::value::Table,
5550
parent: Option<&Category>,
56-
) -> Result<Vec<Category>, Error> {
51+
) -> Result<Vec<Category>> {
5752
let mut result = vec![];
5853

5954
for (slug, details) in categories {
6055
let details = details
6156
.as_table()
62-
.ok_or_else(|| Error::from(format!("category {} was not a TOML table", slug)))?;
57+
.with_context(|| format!("category {} was not a TOML table", slug))?;
6358

6459
let category = Category::from_parent(
6560
slug,
@@ -71,7 +66,7 @@ fn categories_from_toml(
7166
if let Some(categories) = details.get("categories") {
7267
let categories = categories
7368
.as_table()
74-
.ok_or_else(|| format!("child categories of {} were not a table", slug))?;
69+
.with_context(|| format!("child categories of {} were not a table", slug))?;
7570

7671
result.extend(categories_from_toml(categories, Some(&category))?);
7772
}
@@ -82,18 +77,18 @@ fn categories_from_toml(
8277
Ok(result)
8378
}
8479

85-
pub fn sync(toml_str: &str) -> Result<(), Error> {
86-
let conn = db::connect_now().unwrap();
80+
pub fn sync(toml_str: &str) -> Result<()> {
81+
let conn = db::connect_now()?;
8782
sync_with_connection(toml_str, &conn)
8883
}
8984

90-
pub fn sync_with_connection(toml_str: &str, conn: &PgConnection) -> Result<(), Error> {
85+
pub fn sync_with_connection(toml_str: &str, conn: &PgConnection) -> Result<()> {
9186
use crate::schema::categories::dsl::*;
9287
use diesel::dsl::all;
9388
use diesel::pg::upsert::excluded;
9489

9590
let toml: toml::value::Table =
96-
toml::from_str(toml_str).expect("Could not parse categories toml");
91+
toml::from_str(toml_str).context("Could not parse categories toml")?;
9792

9893
let to_insert = categories_from_toml(&toml, None)
9994
.expect("Could not convert categories from TOML")

src/middleware/ember_html.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111
use super::prelude::*;
1212
use std::fmt::Write;
1313

14-
use crate::util::{errors::NotFound, AppResponse, Error};
14+
use crate::util::{errors::NotFound, AppResponse};
1515

16+
use anyhow::{ensure, Result};
1617
use conduit::{Body, HandlerResult};
1718
use conduit_static::Static;
1819
use reqwest::blocking::Client;
@@ -56,7 +57,7 @@ impl Handler for EmberHtml {
5657
// During local fastboot development, forward requests to the local fastboot server.
5758
// In prodution, including when running with fastboot, nginx proxies the requests
5859
// to the correct endpoint and requests should never make it here.
59-
return proxy_to_fastboot(client, req).map_err(box_error);
60+
return proxy_to_fastboot(client, req).map_err(From::from);
6061
}
6162

6263
if req
@@ -86,14 +87,16 @@ impl Handler for EmberHtml {
8687
/// # Panics
8788
///
8889
/// This function can panic and should only be used in development mode.
89-
fn proxy_to_fastboot(client: &Client, req: &mut dyn RequestExt) -> Result<AppResponse, Error> {
90-
if req.method() != conduit::Method::GET {
91-
return Err(format!("Only support GET but request method was {}", req.method()).into());
92-
}
90+
fn proxy_to_fastboot(client: &Client, req: &mut dyn RequestExt) -> Result<AppResponse> {
91+
ensure!(
92+
req.method() == conduit::Method::GET,
93+
"Only support GET but request method was {}",
94+
req.method()
95+
);
9396

9497
let mut url = format!("http://127.0.0.1:9000{}", req.path());
9598
if let Some(query) = req.query_string() {
96-
write!(url, "?{}", query).map_err(|e| e.to_string())?;
99+
write!(url, "?{}", query)?;
97100
}
98101
let mut fastboot_response = client
99102
.request(req.method().into(), &*url)
@@ -107,5 +110,5 @@ fn proxy_to_fastboot(client: &Client, req: &mut dyn RequestExt) -> Result<AppRes
107110
.headers_mut()
108111
.unwrap()
109112
.extend(fastboot_response.headers().clone());
110-
builder.body(Body::from_vec(body)).map_err(Into::into)
113+
Ok(builder.body(Body::from_vec(body))?)
111114
}

src/uploaders.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
use anyhow::Result;
12
use conduit::RequestExt;
23
use flate2::read::GzDecoder;
34
use reqwest::{blocking::Client, header};
45
use sha2::{Digest, Sha256};
56

67
use crate::util::errors::{cargo_err, internal, AppResult, ChainError};
7-
use crate::util::{Error, LimitErrorReader, Maximums};
8+
use crate::util::{LimitErrorReader, Maximums};
89

910
use std::env;
1011
use std::fs::{self, File};
@@ -101,7 +102,7 @@ impl Uploader {
101102
content_length: u64,
102103
content_type: &str,
103104
extra_headers: header::HeaderMap,
104-
) -> Result<Option<String>, Error> {
105+
) -> Result<Option<String>> {
105106
match *self {
106107
Uploader::S3 { ref bucket, .. } => {
107108
bucket.put(
@@ -164,7 +165,7 @@ impl Uploader {
164165
crate_name: &str,
165166
vers: &str,
166167
readme: String,
167-
) -> Result<(), Error> {
168+
) -> Result<()> {
168169
let path = Uploader::readme_path(crate_name, vers);
169170
let content_length = readme.len() as u64;
170171
let content = Cursor::new(readme);

src/util.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use conduit::{header, Body, Response};
44
use rand::{distributions::Uniform, rngs::OsRng, Rng};
55
use serde::Serialize;
66

7-
pub use self::errors::concrete::Error;
87
pub use self::io_util::{read_fill, read_le_u32, LimitErrorReader};
98
pub use self::request_helpers::*;
109
pub use self::request_proxy::RequestProxy;

src/util/errors.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ use diesel::result::Error as DieselError;
2121

2222
use crate::util::AppResponse;
2323

24-
pub(super) mod concrete;
2524
mod json;
2625

2726
pub(crate) use json::{InsecurelyGeneratedTokenRevoked, NotFound, ReadOnlyMode, TooManyRequests};

0 commit comments

Comments
 (0)