异常处理的控制器(ASP.NET MVC) [英] Exception handling in Controller (ASP.NET MVC)

查看:80
本文介绍了异常处理的控制器(ASP.NET MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个异常是由你自己的代码是从控制器的动作称为抛出应当如何运用这种处理?我看到很多的地方有没有在所有的try-catch语句的最佳实践范例。例如,从存储库访问数据:

When an exception is thrown by your own code that's called from an action in a controller how should that be handled? I see a lot of examples of best practices where there are no try-catch statements at all. For example, accessing data from a repository:

public ViewResult Index()
{
    IList<CustomModel> customModels = _customModelRepository.GetAll();
    return View(customModels);
}



显然,这种代码可以如果呼叫到一个数据库抛出一个异常,它无法访问,我们使用的是像实体框架例如一个ORM。

Clearly this code could throw an exception if the call is to a database that it can't access and we are using an ORM like Entity Framework for example.

但是,所有我可以看到将发生的是,异常将向上冒泡并显示一个讨厌错误信息给用户。

However all that I can see will happen is that the exception will bubble up and show a nasty error message to the user.

我知道的HandleError属性,但我知道它主要是用来在发生这未处理的异常将您重定向到一个错误页面。

I'm aware of the HandleError attribute but I understand it's mostly used to redirect you to an error page if an exception that's unhandled occurs.

当然,这个代码可以被包装在一个try-catch,但不能很好地分开,特别是如果你有更多的逻辑:

Of course, this code could be wrapped in a try-catch but doesn't separate nicely, especially if you have more logic:

public ViewResult Index()
{
    if (ValidationCheck())
    {
        IList<CustomModel> customModels = new List<CustomModel>();
        try
        {
            customModels = _customModelRepository.GetAll();
        }
        catch (SqlException ex)
        {
            // Handle exception
        }

        if (CustomModelsAreValid(customModels))
            // Do something
        else
            // Do something else
    }

    return View();
}



此前我已经提取了所有类似的代码数据库调用到一个可能抛出异常DataProvider类用于处理错误和返回的消息回来展示给用户的消息。

Previously I have extracted out all code that could throw exceptions like database calls into a DataProvider class which handles errors and returns messages back for showing messages to the user.

我想知道什么处理这是最好的办法吗?我并不总是想返回一个错误页面,因为一些例外不应该这样做。相反,应该以普通视图显示的错误信息给使用者。 ?是我以前的方法正确,或者是否有更好的解决方案。

I was wondering what the best way of handling this is? I don't always want to return to an error page because some exceptions shouldn't do that. Instead, an error message to the user should be displayed with a normal view. Was my previous method correct or is there a better solution?

推荐答案

我做三件事,以显示对用户更加友好的信息:

I do three things to display more user-friendly messages:


  1. 充分利用全球的异常处理程序。在MVC的情况:的Application_Error Global.asax中。了解如何在这里使用它: http://msdn.microsoft.com /en-us/library/24395wz3(v=vs.100).aspx

  2. 我继承例外成UserFriendlyException。我做我在我所有的基础服务类所能抛出此UserFriendlyException,而不是一个普通的老例外。我总是试图把用户有意义的信息,这些自定义异常。其主要目的是要能做到在的Application_Error方法的异常上的类型检查。对于UserFriendlyExceptions,我只是用我已经设置在我服务的内心深处,喜欢的用户友好的消息:嘿!91度是不是一个有效的纬度值!。如果它是一个常规的例外,那么它的一些情况我还没有处理,所以显示效果较为一般错误消息,如哎呀,出事了!我们会尽我们最大的努力得到固定!

  3. 我也创建一个ErrorController是负责渲染用户友好的观点或JSON。这是它的方法将被从Application_Error事件称为控制器

编辑:
我想我给一提的到的ASP.NET Web API,因为它是密切相关的。由于Web API端点的消费者不一定会浏览器,我喜欢有点不同处理错误。我还是用了FriendlyException(上述#2),但不是重定向到一个ErrorController,我只是让我的所有端点返回某种包含错误属性的基本类型。所以,如果有异常泡一路攀升到Web API控制器,我一定要坚持这个错误的API响应的错误属性。此错误消息将是已经从API控制器依赖于类冒泡友好的消息,或者如果异常类型不是FriendlyException这将是一个通用消息。这样,消费客户端可以直接查询API响应的错误属性是否为空。显示一条消息,如果错误存在,如果不继续如常。这种做法的好处是,因为友好的消息概念,该消息可能会更加有意义给用户比一般的错误!信息。写作与Xamarin,在那里我可以分享我的Web服务和我的iOS / Android应用程序之间我的C#类型的移动应用程序,当我使用这种策略。

I thought I'd give a mention to ASP.NET Web API since it's closely related. Because the consumer of Web API endpoints won't necessarily be a browser, I like to deal with errors a little differently. I still use the "FriendlyException" (#2 above), but instead of redirecting to an ErrorController, I just let all my endpoints return some kind of base type that contains an Error property. So, if an exception bubbles all the way up to the Web API controllers, I make sure to stick that error in the Error property of API response. This error message will either be the friendly message that has bubbled up from the classes the API controller relies on, or it will be a generic message if the exception type is not a FriendlyException. That way, the consuming client can simply check whether or not the Error property of the API response is empty. Display a message if the error is present, proceed as usual if not. The nice thing is that, because of the friendly message concept, the message may be much more meaningful to the user than a generic "Error!" message. I use this strategy when writing mobile apps with Xamarin, where I can share my C# types between my web services and my iOS/Android app.

这篇关于异常处理的控制器(ASP.NET MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆