在ajax调用中从服务层检索自定义异常消息

时间:2015-05-12 11:58:05

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

我使用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等。我想要的是我的服务层抛出的自定义错误消息。

3 个答案:

答案 0 :(得分:1)

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

  1. 我在我的控制器方法和catch块中处理了WebServiceException我通过填写所需的详细信息(主要是来自服务器的自定义异常消息)来重新抛出异常。 控制器方法用" 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. 写了&#34; HandleExceptionAttribute&#34;。在这里,我将我的异常消息包装为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;
    }
    
  4. 我是如何设法从服务层获取自定义错误消息的。希望这是应该怎么做的。如果这里的专家对上述解决方案有任何建议,请发表评论。

    Mythz和Sam感谢您的回答。

答案 1 :(得分:0)

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

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

...这是一篇博客文章,提供了一些额外的细节:

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

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

答案 2 :(得分:0)

您应该能够将错误响应正文解析为JSON并使用以下命令访问ResponseStatus

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