我可以从JsonResult返回自定义错误jQuery的Ajax错误的方法? [英] Can I return custom error from JsonResult to jQuery ajax error method?

查看:146
本文介绍了我可以从JsonResult返回自定义错误jQuery的Ajax错误的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从一个ASP.NET MVC3 JsonResult 方法将错误(或者通过自定义错误信息成功完整,如果需要的话 jQuery.ajax()?理想情况下,我想能够:

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:

  • 仍然抛出异常的服务器上(这是用于记录)
  • 检索客户端上有关该错误的自定义信息

下面是我的code基本版本:

Here is a basic version of my code:

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):

  • 捕获返回的错误信息
    • 在这工作,但异常不会被抛出
    • 然后检查 XHR 在jQuery的错误处理程序
    • xhr.getResponseHeader()等包含默认的ASP.NET错误页,但没有我的信息
    • 我认为这是可能的,但我只是做了错误的?
    • 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?

    推荐答案

    您可以编写一个自定义错误过滤器:

    You could write a custom error filter:

    public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.ExceptionHandled = true;
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        // obviously here you could include whatever information you want about the exception
                        // for example if you have some custom exceptions you could test
                        // the type of the actual exception and extract additional data
                        // For the sake of simplicity let's suppose that we want to
                        // send only the exception message to the client
                        errorMessage = filterContext.Exception.Message
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }
    }
    

    ,然后注册,要么作为一个全球性的过滤器或只适用于你打算调用与AJAX特定的控制器/动作。

    and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.

    和客户端上的:

    $.ajax({
        type: "POST",
        url: "@Url.Action("DoStuff", "My")",
        data: { argString: "arg string" },
        dataType: "json",
        traditional: true,
        success: function(data) {
            //Success handling
        },
        error: function(xhr) {
            try {
                // a try/catch is recommended as the error handler
                // could occur in many events and there might not be
                // a JSON response from the server
                var json = $.parseJSON(xhr.responseText);
                alert(json.errorMessage);
            } catch(e) { 
                alert('something bad happened');
            }
        }
    });
    

    显然,你可能会很快厌倦写重复的错误处理code每个AJAX请求,因此会更好,一旦写出来你的页面上的所有AJAX请求:

    Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:

    $(document).ajaxError(function (evt, xhr) {
        try {
            var json = $.parseJSON(xhr.responseText);
            alert(json.errorMessage);
        } catch (e) { 
            alert('something bad happened');
        }
    });
    

    然后:

    $.ajax({
        type: "POST",
        url: "@Url.Action("DoStuff", "My")",
        data: { argString: "arg string" },
        dataType: "json",
        traditional: true,
        success: function(data) {
            //Success handling
        }
    });
    


    另一种可能性是,以适应一个全球性的异常处理我presented 从而使ErrorController里面你检查它是否在一个AJAX请求,只是返回的异常细节JSON。


    Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.

    这篇关于我可以从JsonResult返回自定义错误jQuery的Ajax错误的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆