在asp.net中,我可以使用以下代码来处理未捕获的错误。
但Android应用程序,我不知道如何编写代码以避免整个应用程序崩溃。
void Application_Error(object sender, EventArgs e)
{
string lr = "\n\n";
string lan = "";
try
{
if (Request.UserLanguages.Length >= 1)
{
for (int i = 0; i <= Request.UserLanguages.Length - 1; i++)
{
lan = lan + " " + Request.UserLanguages[i];
}
}
}
catch
{
}
Exception ex = Server.GetLastError().GetBaseException();
string errorMessage = ex.Message;
string title = "E: " + ex.Message;
string LoginedUser = "";
if (HttpContext.Current.Request.IsAuthenticated)
{
LoginedUser = HttpContext.Current.User.Identity.Name;
}
else
{
LoginedUser = "Anonymous";
}
string content = "Error Message: " + ex.Message
+ lr
+ "Request URL: " + Request.Url.ToString()
+ lr
+ "Request IP: " + Request.UserHostAddress + " Language: " + lan + " Logined User: " + LoginedUser
+ lr;
content = content + "Beijing Time: " + DateTime.UtcNow.AddHours(8).ToString() + " ( UTC+8 ) Web Server Local Time: " + DateTime.Now.ToString() + lr;
//-----------------------------------
StringBuilder message = new StringBuilder();
if (Server != null)
{
Exception ee;
const string exceptionFormat = "{0}: \"{1}\"\r\n{2}\r\n\r\n";
for (ee = Server.GetLastError(); ee != null; ee = ee.InnerException)
{
message.AppendFormat(exceptionFormat,
ee.GetType().Name,
ee.Message,
ee.StackTrace);
}
}
content = content + message.ToString();
//------------------------------------
if (!Request.IsLocal)
{
if (IsCanSend(errorMessage))
{
string fromEmail = ConfigurationManager.AppSettings["FromEmail"];
string toEmail = ConfigurationManager.AppSettings["ToErrorEmail"];
CuiWei.Utility.ATMSendEmail.SendEmail(fromEmail, toEmail, title, content, false, "", new System.Net.Mail.SmtpClient());
}
}
Server.Transfer("~/Error.aspx?ErrorInfo=" + ex.Message);
Server.ClearError();
}
答案 0 :(得分:1)
我在onCreate()中使用此代码:
final UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//TODO Handle Exception
defaultUEH.uncaughtException(thread, ex);
}
});
因此您可以记录错误。如果删除该行
"defaultUEH.uncaughtException(thread, ex);"
它应该继续运行但应用程序可能处于未定义状态,所以要小心。
答案 1 :(得分:0)
您可以根据需要实施此操作。但我建议你看一下ACRA。它具有更多功能,而且非常易于使用。