views:

42

answers:

2

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... Looking for a review. And possibly links to other people's solutions to this problem.

Cheers

+1  A: 

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.

Darin Dimitrov
Thanks Darin. This looks promising and I may go that route. It works for JSON but for text/html (or */*) I can't distinguish between a client that wants an HTML page vs one that wants a PartialView HTML fragment.
Parched Squid