开发者

MVC Controller.OnException for different result types

开发者 https://www.devze.com 2023-01-19 12:15 出处:网络
I\'m trying to find the ideal exception handling strategy for my MVC project. I have done the following and am looking for some feedback.

I'm trying to find the ideal exception handling strategy for my MVC project. I have done the following and am looking for some feedback.

Problem:

I have disparate result types (Pages, Partial Pages, JSON, Files, etc). Controller.OnException() doesn't have an easy way to identify what kind of result the client is expecting. Without anything special I am serving an HTML page when when they want JSON and so forth, which leads to display issues.

Solution:

  1. I have an abstract BaseController that has utility functions like HandleJsonException(), HandlePartialPageException(), HandlePageException(), etc. These functions will:

    a) Hand off to Enterprise Library for logging and notifications.

    b) Set a result view in a format the client expects.

    c) Set an appropriate Http Status Code for the error.

  2. I separate my actions into different controllers based on result type. For example, Instead of AbcController I have AbcPageController and AbcJsonController. The OnException for this controller calls one of the base class utility handlers.

  3. JavaScript (for JSON and Partial Page views) looks at the status code to direct behavior in some cases.

My Concern is that the display logic is dictating the design of the controllers and therefore influencing the routing (not the URL's but the routes obviously). Also, this buggers up prior inheritance strategies with regards to shared OnAuthenticate on base controllers.

Anyways... Loo开发者_开发百科king for a review. And possibly links to other people's solutions to this problem.

Cheers


Controller.OnException() doesn't have an easy way to identify what kind of result the client is expecting

You could use the Accept request header which standards respectful clients send to indicate what content types they support and expect in return. For example if you are using jquery.getJSON() method it will send the following header: Accept: application/json, text/javascript, */*. As you can see application/json is the preferred format here and you could use this information in your controller.


I ended up abandoning this approach.

Handled errors will return an appropriate result directly from the controller action.

Unhandled errors dealt with in Controller.OnException will:

a) set the HttpStatusCode to 500. b) render a full HTML page with our applications error page c) set the handled property to true so custom error pages don't kick in.

If the caller is expecting something other than an HTML page (Ajax JSON, Partial Page, XML, etc) will examine the 500 code and ignore the HTML content.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号