Refactor error logging if Update is failed to parse

This commit is contained in:
Temirkhan Myrzamadi 2020-03-31 21:41:00 +06:00
parent b18cb84df0
commit 46338c464f
4 changed files with 25 additions and 28 deletions

View file

@ -36,18 +36,9 @@ pub async fn webhook<'a>(
let server = warp::post()
.and(warp::body::json())
.map(move |json: serde_json::Value| {
match serde_json::from_str::<Update>(&json.to_string()) {
Ok(update) => tx
.send(Ok(update))
.expect("Cannot send an incoming update from the webhook"),
Err(error) => {
// In this case, please report a bug at https://github.com/teloxide/teloxide/issues !!!
log::error!(
"Cannot parse Update: {}\nError: {}",
json,
error
);
}
if let Ok(update) = Update::try_parse(&json) {
tx.send(Ok(update))
.expect("Cannot send an incoming update from the webhook")
}
StatusCode::OK

View file

@ -166,8 +166,8 @@ pub fn polling(
Err((value, _)) => value["update_id"]
.as_i64()
.expect(
"The 'update_id' field must always exist in \
Update",
"The 'update_id' field must always exist \
in Update",
)
.try_into()
.expect("update_id must be i32"),
@ -178,18 +178,7 @@ pub fn polling(
let updates = updates
.into_iter()
.filter(|update| match update {
Err((value, error)) => {
log::error!("Cannot parse an update.\nError: {:?}\nValue: {}\n\
This is a bug in teloxide, please open an issue here: \
https://github.com/teloxide/teloxide/issues.", error, value);
false
}
Ok(_) => true,
})
.map(|update| {
update.expect("See the previous .filter() call")
})
.filter_map(Result::ok)
.collect::<Vec<Update>>();
updates.into_iter().map(Ok).collect::<Vec<_>>()

View file

@ -52,8 +52,7 @@ impl Request for GetUpdates {
Value::Array(array) => Ok(array
.into_iter()
.map(|value| {
serde_json::from_str(&value.to_string())
.map_err(|error| (value, error))
Update::try_parse(&value).map_err(|error| (value, error))
})
.collect()),
_ => Err(RequestError::InvalidJson(

View file

@ -6,6 +6,7 @@ use crate::types::{
CallbackQuery, Chat, ChosenInlineResult, InlineQuery, Message, Poll,
PollAnswer, PreCheckoutQuery, ShippingQuery, User,
};
use serde_json::Value;
/// This [object] represents an incoming update.
///
@ -30,6 +31,23 @@ pub struct Update {
pub kind: UpdateKind,
}
impl Update {
/// Tries to parse `value` into `Update`, logging an error if failed.
///
/// It is used to implement update listeners.
pub fn try_parse(value: &Value) -> Result<Self, serde_json::Error> {
match serde_json::from_str(&value.to_string()) {
Ok(update) => Ok(update),
Err(error) => {
log::error!("Cannot parse an update.\nError: {:?}\nValue: {}\n\
This is a bug in teloxide, please open an issue here: \
https://github.com/teloxide/teloxide/issues.", error, value);
Err(error)
}
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateKind {