ASP.NET MVC: Signaling to jQuery that an AJAX request has failed with a custom error message
Controller: Products and Action: Save, return a JsonResult. If a trapped exception occurs, i would like to signal that error to the client (ie:jQuery) with a custom error message. How can I do that both on the server and client? Can i utilize the function pointer error in this scenario?
Here's the client code
$.ajax({
url: '/Products/Save',
type: 'POST',
dataType: 'json',
data: ProductJson,
contentType: 'application/json; charset=utf-8',
error: function ()
{
//Display some custom error message that was generated from the server
},
success: function (data) {
// Prod开发者_如何学运维uct was saved! Yay
}
});
The error
function that you refer to is called when the request fails (meaning your controller action did not complete successfully; for example, IIS was down when the user made the request). See http://api.jquery.com/jQuery.ajax/.
If your controller action is successfully contacted and you want to let the client know that something happened inside your controller action that was erroneous, you should return a JsonResult
that contains an Error
or ErrorCode
property that your client side JS will understand.
For example, your controller action could look something like this:
public ActionResult Save()
{
ActionResult result;
try
{
// An error occurs
}
catch(Exception)
{
result = new JsonResult()
{
// Probably include a more detailed error message.
Data = new { Error = true, ErrorMessage = "Product could not be saved." }
};
}
return result;
}
And you would write the following JavaScript to parse that error:
$.ajax({
url: '/Products/Save',
'POST',
'json',
ProductJson,
'application/json; charset=utf-8',
error: function ()
{
//Display some custom error message that was generated from the server
},
success: function (data) {
if (data.Error) {
window.alert(data.ErrorMessage);
}
else {
// Product was saved! Yay
}
}
});
Hope that helps.
I used a clientError attribute to catch the error and ensure it gets sent back as plain text, as well as setting the error code to 500 (so jQuery knows there was a problem and the error function will run:
/// <summary>Catches an Exception and returns just the message as plain text - to avoid full Html
/// messages on the client side.</summary>
public class ClientErrorAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
response.Write(filterContext.Exception.Message);
response.ContentType = MediaTypeNames.Text.Plain;
response.StatusCode = (int)HttpStatusCode.InternalServerError;
response.StatusDescription = filterContext.Exception.Message;
filterContext.ExceptionHandled = true;
}
}
精彩评论