Elmah is cool! Go grab it and learn if you don’t use it yet. Yet, the moment comes when you have plenty of mvc actions returning json and you just want to integrate together that Elmah and MVC error handling to provide some unified JSON error handling in case of handled and unhandled exceptions.
Lets start with a handling code that we might put into every action with the following catch block:
But this “per method” solution doesn’t scale well at all, should you have plenty of those methods. A helper class method to the rescue? Possible. But ASP.NET MVC is so cool! Its stack is ready to solve the task!
So lets delete the above catch and introduce the catch it all error filter by extending the standard HandleErrorAttribute:
Generally, very simple. We check if request is an Ajax request and if it is, we respond with json data generated via the ErrorController (note how context is being passed to the controller) crafted in the following way:
See?! This is our catch block that we don’t need to copy between actions anymore. Of course, those using Ajax in MVC in order to bring html snippets back to browser would have to use/add an extra option and ExecuteResult on some error view instead of JsonResult. This answer on stackoverflow describes the case.
You may consider as well adding Response.StatusCode = 500; just before returning that Json. More on that in the next post on this subject.
With classes above we configure filters in the Global.asax.cs (note that generic HandleErrorAttribute is commented out now, as we have extended it and use our error filter now):
Now, we have json with the Error field returned. And we don’t have to do anything in the action itself!:
With possible handling in browser like this:
One more thing is to test our filter for “non-json” actions. And it works!
This is it, hope it might help someone.
More from me on json in mvc: JSON data islands in ASP.NET MVC