【问题标题】:Retrieve Custom exception message from service layer in ajax call在 ajax 调用中从服务层检索自定义异常消息
【发布时间】:2015-05-12 11:58:05
【问题描述】:

我使用 ServiceStack 框架在 ASP.net MVC5 中开发了我的应用程序。在我的应用程序中,单击按钮时,我会调用返回数据的 ajax 服务器。

this.LoadData = function(){
    $.ajax({
        url: '@Url.Action("SearchCustomer", "Customer")',
        cache: false,
        type: 'GET',
        contentType: 'application/json',
        data: { 'IndexNo': this.IndexNo },
        success: function (result) {
        },
        error: function (xhr, status, error) {
        }
    });
}

在某些情况下,我的服务层会抛出异常(我理解应该将其序列化到 Response DTO 的 ResponseStatus 对象中)。在上述 ajax 调用的错误函数中,我想检索我的服务层抛出的自定义异常消息。我怎样才能做到这一点?上面的状态和错误包含序列化的 ResponseStatus 信息,即“内部服务器错误”、错误代码 500 等。我想要的是我的服务层抛出的自定义错误消息。

【问题讨论】:

    标签: jquery asp.net-mvc-5 asp.net-ajax servicestack


    【解决方案1】:

    我认为您不会找到一个简单的解决方案来从 MVC5 应用程序生成和返回异常。但是,有许多与此主题相关的帖子和​​答案:

    https://stackoverflow.com/a/29481150/571237

    ...这里有一篇博文提供了一些额外的细节:

    http://www.dotnetcurry.com/showarticle.aspx?ID=1068

    一旦您弄清楚如何生成异常并将其返回给 javascript 客户端,只需解析客户端上的响应以提取您在服务器上创建的异常详细信息。如果您不确定上述错误处理程序中的变量是什么,您可以使用 Chrome/Firefox/IE/等中可用的任何可用的 javascript 调试工具检查它们。

    【讨论】:

      【解决方案2】:

      您应该能够将错误响应正文解析为 JSON 并通过以下方式访问 ResponseStatus

      error: function (xhr, status, error) {
          try {
              var response = JSON.parse(xhr.responseText);
              console.log(response.ResponseStatus);
          } catch (e) { }
      }
      

      【讨论】:

        【解决方案3】:

        为了解决我的问题,我做了以下操作:

        1. 我在控制器方法中处理了 WebServiceException,在 catch 块中,我通过填写所需的详细信息(主要是来自服务器的自定义异常消息)重新抛出异常。 控制器方法用“HandleExceptionAttribute”修饰

          [HandleExceptionAttribute]
          public JsonResult SearchCustomer(string IndexNo)
          {
              var client = new JsonServiceClient(ConfigurationManager.AppSettings["baseURL"]);
              GetCustomerResponse response = null;
          
              CustomerViewVM viewVM = null;
              try
              {
                  response = client.Get<GetCustomerResponse>(<RequestDTOObjet>);
          
                  viewVM = response.ToViewCustomerVM();
              }
              catch(WebServiceException ex)
              {
                  Exception e = new Exception(ex.ErrorMessage);
                  e.Data.Add("Operation", "View Customer");
                  e.Data.Add("ErrorCode", ex.StatusCode);
          
                  throw e;
              }
          
              return Json(viewVM, JsonRequestBehavior.AllowGet);
          }
          
        2. 写了“HandleExceptionAttribute”。在这里,我将异常消息包装为 Json 对象并设置状态码。

          public class HandleExceptionAttribute : HandleErrorAttribute
          {
              public override void OnException(ExceptionContext filterContext)
              {
                  if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
                  {
                      if (filterContext.Exception.Data["ErrorCode"] != null)
                      {
                          filterContext.HttpContext.Response.StatusCode = (int)Enum.Parse(typeof(HttpStatusCode), 
                                                                              filterContext.Exception.Data["ErrorCode"].ToString());
                      }
          
                      filterContext.Result = new JsonResult
                      {
                          JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                          Data = new
                          {
                              filterContext.Exception.Message,
                          }
                      };
                      filterContext.ExceptionHandled = true;
                  }
                  else
                  {
                      base.OnException(filterContext);
                  }
              }
          }
          
        3. 然后在我的 ajax 调用错误函数中,我解析包含自定义错误消息信息的 json 对象(我已在属性类中设置)

          error: function (xhr, textStatus, errorThrown) {
               var err = JSON.parse(xhr.responseText);
               var msg = err.Message;
          }
          

        这就是我设法从我的服务层获取自定义错误消息的方式。希望这是应该如何做的。如果这里的专家对上述解决方案有任何建议,请发表评论。

        Mythz 和 Sam 感谢您的回答。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-17
          • 1970-01-01
          • 2018-11-03
          • 2015-11-04
          相关资源
          最近更新 更多