我想发送一条消息,以便在应用程序发生异常时通知用户。我想知道在Java中最好的方法是什么?
在我的程序中,我有一个属性文件调用mail.properties。我在这个文件中声明了一些属性。我成功地从我的属性文件中读取了属性。现在我需要检测程序中的错误并向我的电子邮件帐户发送错误消息
mail.properties
smtpServer = smtp.gmail.com
smtpUsername = myemail@gmail.com
smtpPassword = 123456
smtpPort = 465
在我的main方法中,我已经声明了我的属性文件。我称之为main.java
public class main{
private static String smtpServer;
private static String smtpUsername;
private static String smtpPassword;
private static String smtpPort;
public static void main (String[] args){
//Method for initialize the properties
initialize();
//Code go here (Sending message and stuff)
try{
}
catch(Exception ex)
{
}
}
private static void initialize() throws Exception{
//loadProperties is where I check and get the properties file (no need to worry about it
Properties props = PropertiesUtil.loadProperties("mail.properties");
smtpServer = props.getProperty("smtpServer")
smtpUsername = props.getProperty("smtpUsername")
smtpPassword = props.getProperty("smtpPassword")
smtpPort = props.getProperty("smtpPort")
}
}
答案 0 :(得分:0)
最佳实践是创建一个RuntimeException,将该异常抛到该层的顶部。在图层的顶部将异常传递给实用程序,并将异常消息作为电子邮件正文发送。
答案 1 :(得分:0)
可能只有当它们是RuntimeException子句时才需要通知错误,因为它们表示您无法控制的意外错误。
异常过于分散,您将通过任何错误情况通知用户。我建议你捕获RuntimeException,只检查一些已检查的异常。
GET localhost:1337/items