ASP。NET MVC:通过自定义错误消息向jQuery发出AJAX请求失败的信号

时间:2022-12-04 17:29:58

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?

控制器:产品和操作:保存,返回一个JsonResult。如果出现一个被捕获的异常,我想用一个自定义错误消息向客户端(即jQuery)发送这个错误信号。我如何在服务器和客户端都做到这一点呢?我可以在这个场景中使用函数指针错误吗?

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) {
                    // Product was saved! Yay

                }
            });

2 个解决方案

#1


5  

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/.

当请求失败时调用您引用的错误函数(意味着您的控制器操作没有成功完成;例如,当用户发出请求时,IIS已关闭)。见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.

如果您的控制器动作被成功连接,并且您想让客户知道在您的控制器动作中发生了错误的事情,那么您应该返回一个包含错误或错误代码属性的JsonResult,您的客户端JS将理解该属性。

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:

你会写下面的JavaScript来解析这个错误:

$.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.

希望有帮助。

#2


0  

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:

我使用clientError属性捕获错误并确保它以纯文本形式返回,并将错误代码设置为500(因此jQuery知道有问题,错误函数将运行:

/// <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;
    }
}

#1


5  

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/.

当请求失败时调用您引用的错误函数(意味着您的控制器操作没有成功完成;例如,当用户发出请求时,IIS已关闭)。见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.

如果您的控制器动作被成功连接,并且您想让客户知道在您的控制器动作中发生了错误的事情,那么您应该返回一个包含错误或错误代码属性的JsonResult,您的客户端JS将理解该属性。

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:

你会写下面的JavaScript来解析这个错误:

$.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.

希望有帮助。

#2


0  

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:

我使用clientError属性捕获错误并确保它以纯文本形式返回,并将错误代码设置为500(因此jQuery知道有问题,错误函数将运行:

/// <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;
    }
}