我正在制作一個將錯誤記錄到.log
檔案并將其保存到資料庫的模塊。我只在以下情況下觸發日志記錄:
- 阿賈克斯錯誤。更具體地說,控制器上發生的錯誤 500 狀態代碼。
- 當用戶嘗試訪問 Web 應用程式中不存在的頁面時
問題:
我的第二個目標效果很好,但我的第一個目標有問題。發生內部服務器錯誤時的Server.GetLastError()
回傳。null
除此之外,它不會重定向自定義頁面,而是重定向_ViewStart.cshtml
。
我已經嘗試了這篇文章中的解決方案,但似乎沒有一個有效。它仍然回傳null
而不是例外訊息。我認為這只發生在內部服務器錯誤(500)上。下面是我的代碼、Web 配置和用于模擬錯誤的測驗端點。
全球.asax
void Application_Error(object sender, EventArgs e)
{
try
{
// Code that runs when an unhandled error occurs
HttpException lastErrorWrapper = Server.GetLastError() as HttpException;
Exception lastError = lastErrorWrapper;
if (lastErrorWrapper.InnerException != null)
lastError = lastErrorWrapper.InnerException;
string lastErrorTypeName = lastError.GetType().ToString();
string lastErrorMessage = lastError.Message;
string lastErrorStackTrace = lastError.StackTrace;
// Creation of the log and the log file containing the error
LogFileModel logFile = helpers.CreateLogFile(lastErrorTypeName, lastErrorMessage, lastErrorStackTrace);
helpers.InsertActivityLog_Error(2, "", "Web portal error.", logFile.file, logFile.fileSize, logFile.fileName);
}
catch (Exception) { }
}
網頁配置
<system.web>
<customErrors defaultRedirect="~/Error/ErrorHasOccured" mode="RemoteOnly" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="~/Error/PageNotFound"/>
<error statusCode="500" redirect="~/Error/ErrorHasOccured"/>
</customErrors>
</system.web>
在我的一個控制器上測驗端點
public ActionResult test() {
throw new Exception("This is a test error!");
return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
}
如果我錯過了上面鏈接的帖子中的某些內容,請告訴我。任何幫助,將不勝感激。謝謝!
uj5u.com熱心網友回復:
Server.GetLastError()
由于某種原因,ASP.Net 似乎不允許出現錯誤 500 。如果有人知道為什么會這樣或者我錯了,請隨時在此處發表評論,以便每個人都知道。
MS Docs 沒有向我清楚地解釋為什么會這樣,所以我做了一個解決方法。我使用了object sender
包含我需要的資訊的引數。我從那里獲取錯誤訊息和堆疊跟蹤并將其傳遞給我的函式,該函式將日志檔案創建到資料庫。
void Application_Error(object sender, EventArgs e)
{
var senderValue = (HttpApplication)sender;
string lastErrorTypeName = string.Empty;
string lastErrorMessage = string.Empty;
string lastErrorStackTrace = string.Empty;
try
{
HttpException lastErrorWrapper = Server.GetLastError() as HttpException;
Exception lastError = lastErrorWrapper;
if (lastErrorWrapper.InnerException != null)
lastError = lastErrorWrapper.InnerException;
lastErrorTypeName = lastError.GetType().ToString();
lastErrorMessage = lastError.Message;
lastErrorStackTrace = lastError.StackTrace;
}
catch (Exception)
{
lastErrorTypeName = "InternalError";
lastErrorMessage = senderValue.Context.Error.Message;
lastErrorStackTrace = senderValue.Context.Error.StackTrace;
}
// Create log file and store to database
try
{
LogFileModel logFile = helpers.CreateLogFile(lastErrorTypeName, lastErrorMessage, lastErrorStackTrace);
helpers.InsertActivityLog_Error(2, "", "Web portal error.", logFile.file, logFile.fileSize, logFile.fileName);
}
catch (Exception) { }
}
我知道這不如使用Server.GetLastError()
. 如果您找到更好的解決方案,請隨時回答。
謝謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490424.html