asp.net-mvc asp.net mvc 3 中的错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5995776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:11:50  来源:igfitidea点击:

Error Handling in asp.net mvc 3

asp.net-mvcasp.net-mvc-3error-handlingninject

提问by Shawn Mclean

Is there a built in or a proper way to handle errors in asp.net mvc 3?

是否有内置或正确的方法来处理 asp.net mvc 3 中的错误?

This is what I want to do:

这就是我想要做的:

  1. If the application crashes, or throws an error, it goes to a specific error page.
  2. I can throw my own error from the controller action. (and it goes to an error page).
  1. 如果应用程序崩溃或抛出错误,它会转到特定的错误页面。
  2. 我可以从控制器动作中抛出我自己的错误。(并转到错误页面)。

I found the following ways:

我找到了以下方法:

  1. I see there is a long way to do it here. (for v1 and v2 but also applies to v3).
  2. Using errorhandle attribute here.
  1. 我看到有一个很长的路要走做到这一点 在这里。(适用于 v1 和 v2,但也适用于 v3)。
  2. 在这里使用 errorhandle 属性。

How do I handle this the proper way?

我如何以正确的方式处理这个问题?

If the solution is similar or is like #1 in the list above, I am using ninject and I have not created a base class. How do I still do this?

如果解决方案与上面列表中的#1 类似或类似,我使用的是ninject 并且我还没有创建基类。我该怎么做?

采纳答案by Sunil

For Global Error Handling
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.

Make sure that Error.cshtml Layout is not null.
[It sould be something like: @{ Layout = "~/Views/Shared/_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-

对于全局错误处理,
您只需更改 web.config 页面中的 customErrors mode="On"
错误将通过 Error.cshtml 显示在共享文件夹中。

确保 Error.cshtml Layout 不是 null
[它应该是这样的:@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
或者删除布局=零码块]
为Error.cshtml样品标记: -

@{ Layout = "~/Views/Shared/_Layout.cshtml"; } 

@model System.Web.Mvc.HandleErrorInfo

<!DOCTYPE html>
<html>
<head>
    <title>Error</title>
</head>
<body>
    <h2>
        Sorry, an error occurred while processing your request.
    </h2>
    <p>Controller Name: @Model.ControllerName</p>
    <p>Action Name : @Model.ActionName</p>
    <p>Message: @Model.Exception.Message</p>
</body>
</html>

For Specific Error Handling
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:

对于特定错误处理
将 HandleError 属性添加到控制器类中的特定操作。为该特定错误提供“视图”和“异常类型”。
一个示例 NotImplemented 异常处理程序:

public class MyController: Controller
    {
        [HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
        public ActionResult Index()
        {
            throw new NotImplementedException("This method is not implemented.");
            return View();
        }
}

回答by Jerad Rose

I would suggest implementing a custom HandleErrorAttribute action filter.

我建议实现自定义 HandleErrorAttribute 操作过滤器。

See this link for more details:
http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx

有关更多详细信息,请参阅此链接:http:
//msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx

Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.

设置 HandleErrorAttribute 操作过滤器可以让您完全控制过滤器处理哪些操作,并且可以轻松地在控制器级别进行设置,甚至可以通过在自定义基本控制器上进行设置而在站点级别进行设置,并拥有您所有的控制器继承自基本控制器。

Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.

我对此做的其他事情是,我有一个单独的 HandleJsonErrorAttribute,它通过返回 Json 响应而不是自定义页面来响应 Ajax 调用。

UPDATE:

更新:

Per some questions below, here is an example of a HandleJsonErrorAttributethat I use:

根据下面的一些问题,这是HandleJsonErrorAttribute我使用的一个示例:

public class HandleJsonErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var serviceException = filterContext.Exception as ServiceException;

        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };

        filterContext.ExceptionHandled = true;
    }
}

And here is the jQuery that I use to handle these unhanded exceptions:

这是我用来处理这些未经处理的异常的 jQuery:

$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
    showPopdown($.parseJSON(jqXHR.responseText).message);
});

This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.

这允许我的 Ajax 方法非常轻量级——它们只处理返回正常的 Json,并且在发生未经处理的异常时,带有错误状态代码的消息被包裹在 Json 中并返回。

Also, in my implementation, I have a custom ServiceExceptionthat I throw from services, and this sends the message from the service layer instead of a generic message.

此外,在我的实现中,我有一个ServiceException从服务抛出的自定义,它从服务层发送消息而不是通用消息。

回答by thitemple

The easiest way I think you can do that is using the elmah library.

我认为最简单的方法是使用 elmah 库。

Take a look at this: http://code.google.com/p/elmah/wiki/MVCand this http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

看看这个:http: //code.google.com/p/elmah/wiki/MVC和这个 http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

回答by Tien Do

I think the easiest way is using ExceptionHandler attribute since it's ready to use anytime you create a new ASP.NET MVC 3 project. You can still configure Web.config to use a custom error page and handling exceptions in global Application_Error method as usual but when an exception occurs the URL is not displayed as nice as the new MVC 3's way.

我认为最简单的方法是使用 ExceptionHandler 属性,因为它随时可以在您创建新的 ASP.NET MVC 3 项目时使用。您仍然可以像往常一样将 Web.config 配置为使用自定义错误页面并在全局 Application_Error 方法中处理异常,但是当发生异常时,URL 的显示方式不如新 MVC 3 的方式好。

回答by pravin

you can create custom exception in MVC if you want to customize a way of exception handling. you can find useful post here . http://www.professionals-helpdesk.com/2012/07/creating-custom-exception-filter-in-mvc.html

如果要自定义异常处理方式,可以在 MVC 中创建自定义异常。你可以在这里找到有用的帖子。 http://www.professionals-helpdesk.com/2012/07/creating-custom-exception-filter-in-mvc.html