How do I handle exceptions thrown in a controller when jquery ajax calls an action?
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
On the client side, I will call a function on the ajax error.
On the server side, Do I need to write a custom actionfilter?
Best Answer
If the server sends some status code different than 200, the error callback is executed:
and to register a global error handler you could use the
$.ajaxSetup()
method:Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
and then decorate your controller action with this attribute:
and finally invoke it: