Skip to content

Commit

Permalink
增加异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
ipconfiger committed Apr 3, 2023
1 parent 28caa34 commit edd2b0f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cron_trigger"
version = "0.1.3"
version = "0.1.4"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
16 changes: 11 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use tokio::fs::File;
use tokio::io::{self, AsyncBufReadExt, BufReader};
use chrono::{DateTime, Utc};
use std::str::FromStr;
use std::panic;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
Expand Down Expand Up @@ -36,17 +37,17 @@ fn send_web(to_addr: String, content: String) {

fn send_mail(config: &Config, to_addr: String, title: String, content: String) {
// 设置发件人邮箱地址
let from = config.from_addr.parse().unwrap();
let from = config.from_addr.parse().expect("Invalid from addr");
// 设置收件人邮箱地址
let to = to_addr.parse().unwrap();
let to = to_addr.parse().expect("Invalid target addr");
// 创建邮件
let email = Message::builder()
.from(from)
.to(to)
.subject(title)
.header(ContentType::TEXT_PLAIN)
.body(content)
.unwrap();
.expect("Invalid mail");
// 设置SMTP服务器地址和端口号
let smtp_server = config.smtp.clone();
let smtp_port = config.smtp_port;
Expand All @@ -56,7 +57,7 @@ fn send_mail(config: &Config, to_addr: String, title: String, content: String) {

// 创建SMTP传输对象
let smtp_transport = SmtpTransport::starttls_relay(smtp_server.as_str())
.unwrap()
.expect("create mail transport error!")
.credentials(Credentials::new(username.to_string(), password.to_string()))
.port(smtp_port).build();
// 发送邮件
Expand Down Expand Up @@ -144,7 +145,12 @@ fn send_notification(config_path: PathBuf, title: &str, body: &str) {
},
"mail"=>{
println!("get mail hook, send mail");
send_mail(&config, item.address.clone(), title.to_string(), body.to_string());
let result = panic::catch_unwind(|| {
send_mail(&config, item.address.clone(), title.to_string(), body.to_string());
});
if let Err(err) = result {
println!("Caught a panic: {:?}", err);
}
},
_=>{}
}
Expand Down

0 comments on commit edd2b0f

Please sign in to comment.