Improve error handling

This commit is contained in:
Sakuhl 2018-01-14 15:19:48 +01:00
parent eaad5cd6c6
commit 8506121986

View File

@ -6,21 +6,30 @@ use serde_json::Value;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate failure;
use failure::Error;
use std::collections::HashMap;
pub fn player(name: &str) -> Result<Player, Error> {
let resp = reqwest::get(&format!("https://api.wynncraft.com/public_api.php?action=playerStats&command={}", name))?;
let resp = reqwest::get(&format!("https://api.wynncraft.com/public_api.php?action=playerStats&command={}", name))?.text().unwrap();
Ok(serde_json::from_reader(resp)?)
if let Ok(error) = serde_json::from_str::<APIError>(&resp) {
bail!("API error ({})", error.error);
} else {
Ok(serde_json::from_str(&resp)?)
}
}
pub fn guild(name: &str) -> Result<Guild, Error> {
let resp = reqwest::get(&format!("https://api.wynncraft.com/public_api.php?action=guildStats&command={}", name))?;
pub fn guild(name: &str) -> Result<Option<Guild>, Error> {
let resp = reqwest::get(&format!("https://api.wynncraft.com/public_api.php?action=guildStats&command={}", name))?.text().unwrap();
Ok(serde_json::from_reader(resp)?)
if let Ok(error) = serde_json::from_str::<APIError>(&resp) {
bail!("API error ({})", error.error);
} else {
Ok(serde_json::from_str(&resp)?)
}
}
pub fn guild_by_prefix(prefix: &str) -> Result<Option<GuildEntry>, Error> {
@ -41,6 +50,11 @@ pub fn guild_leaderboard() -> Result<Top100Guilds, Error> {
Ok(serde_json::from_reader(resp)?)
}
#[derive(Deserialize)]
struct APIError {
error: String
}
#[derive(Deserialize)]
pub struct Top100Guilds {
pub data: Vec<GuildEntry>