ASP.NET MVC OnException and Ajax Form onFailure
The situation I have is, I am handling the OnException in my controller. Depending on the type of the exception, I would like to return a javascript result. The action method that threw the exception was called by submitting an ajax form. The ajax form handles the success event. In my OnException method, I set ExceptionHandled = true for all examples I have seen. The problem is even that an exception was thrown and I returned a JavascriptResult that called the success method and the returned javascript was not executed. Any suggestions as to why this is happening and how I can get the JavascriptResult to execute.
Here's the sequence of events:
- browser sent ajax request
- the action method on the server took over and threw an exception.
- Your OnException method got a chance to view the exception and decided to set ExceptionHandled = true.
- your OnException method returned JavascriptResult
- since the ExceptionHandled parameter is set to true, MVC stops the exception handling chain at this point and returns a JavascriptResult to the browser with an HTTP 200 OK result code
- The ajax code in the browser receives the result and interprets it as an indication that everything is fine; it then calls OnComplete and then OnSuccess.
Your options:
-
Set status code 500 in response before returning from OnException. The browser will call OnComplete, then OnFailure.
-
Process the return value in OnComplete, not OnSuccess, and then return false to indicate that OnSuccess should not be called.
source to share