asp.net-mvc asp.net mvc 错误处理的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4523831/
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
Best practices for asp.net mvc error handling
提问by noname.cs
I'm looking for a standard way to handle errors in asp.net mvc 2.0 or 3.0
我正在寻找一种标准方法来处理 asp.net mvc 2.0 或 3.0 中的错误
- 404 error handler
- Controller scope exception error handler
- Global scope exception error handler
- 404 错误处理程序
- 控制器范围异常错误处理程序
- 全局范围异常错误处理程序
回答by Crab Bucket
For controller scope errors try using a custom Exception attribute i.e.
对于控制器范围错误,请尝试使用自定义异常属性,即
public class RedirectOnErrorAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Don't interfere if the exception is already handled
if(filterContext.ExceptionHandled)
return;
//.. log exception and do appropriate redirects here
}
}
Then decorate the controllers with the attribute and error handling should be yours
然后用属性装饰控制器,错误处理应该是你的
[RedirectOnError]
public class TestController : Controller
{
//.. Actions etc...
}
Doesn't help if the error is with the routing though - i.e. it can't find a controller in the first place. For that try the Application Error handler in Global.asax i.e.
如果错误与路由有关,则无济于事 - 即它首先找不到控制器。为此,请尝试 Global.asax 中的应用程序错误处理程序,即
protected void Application_Error(object sender, EventArgs e)
{
//.. perhaps direct to a custom error page is here
}
I don't know if it's 'best practice' though. Does work.
我不知道这是否是“最佳实践”。行得通。
回答by macou
Not sure about best practices and depending on what you want to do with the error, would a simple solution not be to use the customErrors setting in the web.config file?
不确定最佳实践并取决于您想对错误做什么,一个简单的解决方案不是使用 web.config 文件中的 customErrors 设置吗?
For catching unhandled errors I sometimes make use of the Application_Error method in the Global.asax file.
为了捕捉未处理的错误,我有时会使用 Global.asax 文件中的 Application_Error 方法。
Also, Take a look at this SO post
另外,看看this SO post
回答by Vasiliy R
Hereis the most detailed answer to "404" part of your question. Despite the main topic of that is 404 it would give you an idea about how to apply that to other error types.
这是您问题的“404”部分的最详细答案。尽管它的主要主题是 404,但它会让您了解如何将其应用于其他错误类型。
Although, I can't state it clearly as the "best practice" since you'll need a layer supertype controller with that approach. I'd better catch those HttpException
s in Global.asax
. But for the most part it is a great guide.
虽然,我不能清楚地将其声明为“最佳实践”,因为您将需要一个具有这种方法的层超类型控制器。我最好HttpException
在Global.asax
. 但在大多数情况下,它是一个很好的指南。
As for arbitrary exceptions throughout your MVC-app - don't forget about HandleErrorAttribute
.
至于整个 MVC 应用程序中的任意异常 - 不要忘记HandleErrorAttribute
.