ASP.NET MVC HandleError


110

如何处理[HandleError]asp.net MVC Preview 5中的过滤器?
我在Web.config文件中设置了customErrors

<customErrors mode="On" defaultRedirect="Error.aspx">
  <error statusCode="403" redirect="NoAccess.htm"/>
  <error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>

并将[HandleError]放在我的Controller类上方,如下所示:

[HandleError]
public class DSWebsiteController: Controller
{
    [snip]
    public ActionResult CrashTest()
    {
        throw new Exception("Oh Noes!");
    }
}

然后,让我的控制器从此类继承,并对其调用CrashTest()。Visual Studio停止显示错误,并按f5键继续,然后重新路由到Error.aspx?aspxerrorpath = / sxi.mvc / CrashTest(其中sxi是使用的控制器的名称。当然,找不到该路径,我得到了“'/'应用程序中的服务器错误。” 404。

该站点从预览3移植到5。除了错误处理之外,其他所有东西都可以运行(移植工作不多)。当我创建一个完整的新项目时,错误处理似乎可以正常工作。

有想法吗?

-注意-
由于此问题现在已超过3K,因此我认为放入当前使用的内容(ASP.NET MVC 1.0)将是有益的。在mvc contrib项目中,有一个出色的属性称为“ RescueAttribute”,您也应该检查一下它;)


Answers:


158
[HandleError]

当您仅向类(或为此的操作方法)提供HandleError属性时,则当发生未处理的异常时,MVC将首先在Controller的View文件夹中查找名为“ Error”的对应View。如果找不到该文件,它将继续在“共享视图”文件夹中查找(默认情况下,该文件夹中应包含Error.aspx文件)

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")]

您还可以将其他属性与有关您要查找的异常类型的特定信息堆叠在一起。那时,您可以将错误定向到默认视图以外的特定视图。

有关更多信息,请查看Scott Guthrie的博客文章


1
感谢您提供更多信息。我不知道我做错了什么,但是我创建了一个新项目,在其中移植了所有现有的视图,控制器和模型,现在可以使用了。虽然不知道选择性视图。
鲍里斯·卡伦斯

如果需要记录这些异常,这是否是在视图后添加代码的地方?
Peter J

6
标志性的,这是我对您的评论“迟到总比没有好”的答复:您可以代替HandleErrorAttribute的子类,并覆盖其“ OnException”方法:然后,插入所需的任何日志记录或自定义操作。然后,您可以完全处理异常(将context.ExceptionHandled设置为true),或为此推迟到基类自己的OnException方法。这是一篇很好的文章,可能会对您有所帮助:blog.dantup.me.uk/2009/04/…– Funka
2009年

我有很多控制器,所以我可以global.asax这样在内部处理此操作以向用户显示消息吗?
shaijut

@如何使用与PartialView相同的错误页面并在异常发生后在模式对话框中呈现它?您能否在回答中提供一个例子?我要实现的目标已在MVC中使用PartialView进行全局错误处理中进行了解释。
杰克


14

解决HTTP错误代码到500的方法,这是一个称为[ERROR]的属性,将其应用于操作

public class Error: System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
    {

            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {
                filterContext.ExceptionHandled = true;

            }
            base.OnException(filterContext);
            //OVERRIDE THE 500 ERROR  
           filterContext.HttpContext.Response.StatusCode = 200;
    }

    private static void RaiseErrorSignal(Exception e)
    {
        var context = HttpContext.Current;
      // using.Elmah.ErrorSignal.FromContext(context).Raise(e, context);
    } 

}

//例:

[Error]
[HandleError]
[PopulateSiteMap(SiteMapName="Mifel1", ViewDataKey="Mifel1")]
public class ApplicationController : Controller
{
}

12

MVC中的属性在get和post方法的错误处理中非常有用,它还可以跟踪ajax调用

在您的应用程序中创建一个基本控制器,并在您的主控制器(EmployeeController)中继承它。

公共类EmployeeController:BaseController

在基本控制器中添加以下代码。

/// <summary>
/// Base Controller
/// </summary>
public class BaseController : Controller
{       
    protected override void OnException(ExceptionContext filterContext)
    {
        Exception ex = filterContext.Exception;

        //Save error log in file
        if (ConfigurationManager.AppSettings["SaveErrorLog"].ToString().Trim().ToUpper() == "TRUE")
        {
            SaveErrorLog(ex, filterContext);
        }

        // if the request is AJAX return JSON else view.
        if (IsAjax(filterContext))
        {
            //Because its a exception raised after ajax invocation
            //Lets return Json
            filterContext.Result = new JsonResult()
            {
                Data = Convert.ToString(filterContext.Exception),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();

            filterContext.Result = new ViewResult()
            {
                //Error page to load
                ViewName = "Error",
                ViewData = new ViewDataDictionary()
            };

            base.OnException(filterContext);
        }
    }

    /// <summary>
    /// Determines whether the specified filter context is ajax.
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    private bool IsAjax(ExceptionContext filterContext)
    {
        return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }

    /// <summary>
    /// Saves the error log.
    /// </summary>
    /// <param name="ex">The ex.</param>
    /// <param name="filterContext">The filter context.</param>
    void SaveErrorLog(Exception ex, ExceptionContext filterContext)
    {
        string logMessage = ex.ToString();

        string logDirectory = Server.MapPath(Url.Content("~/ErrorLog/"));

        DateTime currentDateTime = DateTime.Now;
        string currentDateTimeString = currentDateTime.ToString();
        CheckCreateLogDirectory(logDirectory);
        string logLine = BuildLogLine(currentDateTime, logMessage, filterContext);
        logDirectory = (logDirectory + "\\Log_" + LogFileName(DateTime.Now) + ".txt");

        StreamWriter streamWriter = null;
        try
        {
            streamWriter = new StreamWriter(logDirectory, true);
            streamWriter.WriteLine(logLine);
        }
        catch
        {
        }
        finally
        {
            if (streamWriter != null)
            {
                streamWriter.Close();
            }
        }
    }

    /// <summary>
    /// Checks the create log directory.
    /// </summary>
    /// <param name="logPath">The log path.</param>
    bool CheckCreateLogDirectory(string logPath)
    {
        bool loggingDirectoryExists = false;
        DirectoryInfo directoryInfo = new DirectoryInfo(logPath);
        if (directoryInfo.Exists)
        {
            loggingDirectoryExists = true;
        }
        else
        {
            try
            {
                Directory.CreateDirectory(logPath);
                loggingDirectoryExists = true;
            }
            catch
            {
            }
        }

        return loggingDirectoryExists;
    }

    /// <summary>
    /// Builds the log line.
    /// </summary>
    /// <param name="currentDateTime">The current date time.</param>
    /// <param name="logMessage">The log message.</param>
    /// <param name="filterContext">The filter context.</param>       
    string BuildLogLine(DateTime currentDateTime, string logMessage, ExceptionContext filterContext)
    {
        string controllerName = filterContext.RouteData.Values["Controller"].ToString();
        string actionName = filterContext.RouteData.Values["Action"].ToString();

        RouteValueDictionary paramList = ((System.Web.Routing.Route)(filterContext.RouteData.Route)).Defaults;
        if (paramList != null)
        {
            paramList.Remove("Controller");
            paramList.Remove("Action");
        }

        StringBuilder loglineStringBuilder = new StringBuilder();

        loglineStringBuilder.Append("Log Time : ");
        loglineStringBuilder.Append(LogFileEntryDateTime(currentDateTime));
        loglineStringBuilder.Append(System.Environment.NewLine);

        loglineStringBuilder.Append("Username : ");
        loglineStringBuilder.Append(Session["LogedInUserName"]);
        loglineStringBuilder.Append(System.Environment.NewLine);

        loglineStringBuilder.Append("ControllerName : ");
        loglineStringBuilder.Append(controllerName);
        loglineStringBuilder.Append(System.Environment.NewLine);

        loglineStringBuilder.Append("ActionName : ");
        loglineStringBuilder.Append(actionName);
        loglineStringBuilder.Append(System.Environment.NewLine);

        loglineStringBuilder.Append("----------------------------------------------------------------------------------------------------------");
        loglineStringBuilder.Append(System.Environment.NewLine);

        loglineStringBuilder.Append(logMessage);
        loglineStringBuilder.Append(System.Environment.NewLine);
        loglineStringBuilder.Append("==========================================================================================================");

        return loglineStringBuilder.ToString();
    }

    /// <summary>
    /// Logs the file entry date time.
    /// </summary>
    /// <param name="currentDateTime">The current date time.</param>
    string LogFileEntryDateTime(DateTime currentDateTime)
    {
        return currentDateTime.ToString("dd-MMM-yyyy HH:mm:ss");
    }

    /// <summary>
    /// Logs the name of the file.
    /// </summary>
    /// <param name="currentDateTime">The current date time.</param>
    string LogFileName(DateTime currentDateTime)
    {
        return currentDateTime.ToString("dd_MMM_yyyy");
    }

}

===============================================

查找目录:Root / App_Start / FilterConfig.cs

添加以下代码:

/// <summary>
/// Filter Config
/// </summary>
public class FilterConfig
{
    /// <summary>
    /// Registers the global filters.
    /// </summary>
    /// <param name="filters">The filters.</param>
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

跟踪AJAX错误:

在布局页面加载中调用CheckAJAXError函数。

function CheckAJAXError() {
    $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {

        var ex;
        if (String(thrownError).toUpperCase() == "LOGIN") {
            var url = '@Url.Action("Login", "Login")';
            window.location = url;
        }
        else if (String(jqXHR.responseText).toUpperCase().indexOf("THE DELETE STATEMENT CONFLICTED WITH THE REFERENCE CONSTRAINT") >= 0) {

            toastr.error('ReferanceExistMessage');
        }
        else if (String(thrownError).toUpperCase() == "INTERNAL SERVER ERROR") {
            ex = ajaxSettings.url;
            //var url = '@Url.Action("ErrorLog", "Home")?exurl=' + ex;
            var url = '@Url.Action("ErrorLog", "Home")';
            window.location = url;
        }
    });
};

您正在泄漏有关AJAX请求的异常详细信息,但并非总是如此。您的日志记录代码不是线程安全的。您假设有一个错误视图并返回它,而没有更改响应代码。然后,您去检查JavaScript中的某些错误字符串(本地化是什么?)。基本上,您将重复现有答案已经说过的内容:“重写OnException以处理异常”,但是显示了一个非常糟糕的实现。
CodeCaster

什么是@ School.Resource.Messages.ReferanceExist参数?
杰克

@CodeCaster您知道在ASP.NET MVC中与AJAX一起使用这种错误处理方法的更好方法吗?有什么帮助吗?
杰克

返回HTTP预期的400或500。不要在响应正文中挖掘特定的字符串。
CodeCaster

@CodeCaster请问有关此问题的MVC中使用PartialView进行的全局错误处理
杰克

4

您缺少Error.aspx :)在预览5中,该文件位于您的“视图/共享”文件夹中。只需从新的Preview 5项目中复制它即可。


感谢您的答复,但我已经复制了Error.aspx页面。确实确实是我通常会忘记的东西,但这次不是。:P
鲍里斯·卡伦斯

-1
    [HandleError]
    public class ErrorController : Controller
    {        
        [AcceptVerbs(HttpVerbs.Get)]
        public ViewResult NotAuthorized()
        {
            //401
            Response.StatusCode = (int)HttpStatusCode.Unauthorized;

        return View();
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public ViewResult Forbidden()
    {
        //403
        Response.StatusCode = (int)HttpStatusCode.Forbidden;

        return View();
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public ViewResult NotFound()
    {
        //404
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View();
    }

    public ViewResult ServerError()
    {
        //500
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View();
    }

}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.