私は自分のコントローラーでエラーを処理して[CustomErrorHandleAttribute]
いますが、自分のアクションに例外がある場合の対処方法を書いています。コードにエラーがなくても、customerrorhandle にリダイレクトされ、エラーがスローされます。なぜこれを行っているのか、エラーを見つけることができません。
これが私のコードです:
namespace ExceptionHandlingInMVC.Controllers
{
[CustomHandleError]
public class HomeController : Controller
{
//
// GET: /Home/
public object Index()
{
try
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Current time is:" + DateTime.Now.ToLongTimeString();
var x = 10;
var y = 10;
var result = x / y;
ViewData["Result"] = result;
return View();
}
catch (Exception e)
{
throw e;
}
}
[CustomHandleError]
public object About()
{
ViewData["Title"] = "About Page";
return View();
}
}
public class ErrorPresentation
{
public String ErrorMessage { get; set; }
public Exception TheException { get; set; }
public Boolean ShowMessage { get; set; }
public Boolean ShowLink { get; set; }
}
}
私が書いた CustomHandleErrorAttribute:
namespace ExceptionHandlingInMVC
{
/// <summary>
/// This attribute (AOP) filter is used to override the Error handling and make sure that all erros are recorded in the event logs, so that they can in turn be picked up by
/// our SIEM tool so that we a) stop customers seing a bad error message and b) we are capturing all the events that happen and c) improives security for
/// by preventing a hacker from seing s=details of how our application is put together
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class CustomHandleErrorAttribute : ActionFilterAttribute
{
/// <summary>
/// This event is called when the action is called i.e. an error has just occured
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
try
{
// Bail if we can't do anything; app will crash.
if (filterContext == null)
return;
// since we're handling this, log to ELMAH(Error logging modules and handler)
var ex = filterContext.Exception ?? new Exception("No further information exists.");
WriteToEventLog(ex);
filterContext.ExceptionHandled = true;
var data = new ErrorPresentation
{
ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
TheException = ex,
ShowMessage = filterContext.Exception != null,
ShowLink = false
};
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Home/ErrorPage.aspx"
};
}
catch (Exception exception)
{
throw;
}
}
/// <summary>
/// This method writes the exception to the event log we have specified in the web.config or the app.config
/// </summary>
/// <param name="exception"></param>
public void WriteToEventLog(Exception exception)
{
// pick up which machine we are on, this will already be set for all websites
var machineName = ConfigurationManager.AppSettings["MachineName"];
// PIck up the eventlog we are going to write to
var eventLogName = ConfigurationManager.AppSettings["EventLogName"];
EventLog.WriteEntry("abc", exception.Message, EventLogEntryType.Error);
}
}
}