How can I pass custom error information from an ASP.NET MVC3 JsonResult
method to the error
(or success
or complete
, if need be) function of jQuery.ajax()
? Ideally I'd like to be able to:
- Still throw the error on the server (this is used for logging)
- Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
- Returning error info from
catch
block- This works, but the exception can't be thrown
- Editing HTTP response in
catch
block- Then inspected
xhr
in the jQuery error handler xhr.getResponseHeader()
, etc. contained the default ASP.NET error page, but none of my information- I think this may be possible, but I just did it wrong?
- Then inspected