MVC Controller.OnException for different result types
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:
I have an abstract
BaseController
that has utility functions likeHandleJsonException()
,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.
I separate my actions into different controllers based on result type. For example, Instead of
AbcController
I haveAbcPageController
andAbcJsonController
. The OnException for this controller calls one of the base class utility handlers.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.
精彩评论