关于asp.net mvc 3:Ajax报告错误调用了MVC中的PartialView方法

Reporting errors from Ajax invoked PartialView methods in MVC

如果正常的页面加载错误,我可以通过Error视图和HandleErrorInfo模型向用户报告异常详细信息。

如果一个ajax调用预期有Json结果错误,我可以显式地处理错误并将详细信息传递给客户:

1
2
3
4
5
6
7
8
9
10
11
12
public JsonResult Whatever()
{
    try
    {
        DoSomething();
        return Json(new { status ="OK" });
    }
    catch (Exception e)
    {
        return Json(new { status ="Error", message = e.Message });
    }
}

所以,我的问题是,我看不到任何方法来报告从Ajax调用到返回部分视图的操作的错误详细信息。

1
2
3
4
5
6
7
8
9
$.ajax({
    url: 'whatever/trevor',
    error: function (jqXHR, status, error) {
        alert('An error occured: ' + error);
    },
    success: function (html) {
        $container.html(html);
    }
});

这只会报告一个HTTP错误代码(例如,内部服务器错误),这对客户端没有帮助。是否有一些巧妙的技巧来传递成功的partialview(html)结果或错误消息?

ViewResult显式地评估HTML,并将其作为Json对象的一部分返回,同时返回一个状态似乎太难闻了。是否有处理此方案的既定模式?


控制器的动作:

1
2
3
4
5
6
7
8
9
10
11
12
13
public ActionResult Foo()
{
    // Obviously DoSomething could throw but if we start
    // trying and catching on every single thing that could throw
    // our controller actions will resemble some horrible plumbing code more
    // than what they normally should resemble: a.k.a being slim and focus on
    // what really matters which is fetch a model and pass to the view

    // Here you could return any type of view you like: JSON, HTML, XML, CSV, PDF, ...

    var model = DoSomething();
    return PartialView(model);
}

然后我们定义全局错误处理程序,我们的应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;
    Response.Clear();
    Server.ClearError();

    if (new HttpRequestWrapper(Request).IsAjaxRequest())
    {
        // Some error occurred during the execution of the request and
        // the client made an AJAX request so let's return the error
        // message as a JSON object but we could really return any JSON structure
        // we would like here

        Response.StatusCode = 500;
        Response.ContentType ="application/json";
        Response.Write(new JavaScriptSerializer().Serialize(new
        {
            errorMessage = exception.Message
        }));
        return;
    }

    // Here we do standard error handling as shown in this answer:
    // http://stackoverflow.com/q/5229581/29407

    var routeData = new RouteData();
    routeData.Values["controller"] ="Errors";
    routeData.Values["action"] ="General";
    routeData.Values["exception"] = exception;
    Response.StatusCode = 500;
    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();
        switch (Response.StatusCode)
        {
            case 404:
                routeData.Values["action"] ="Http404";
                break;
            case 500:
                routeData.Values["action"] ="Http500";
                break;
        }
    }

    IController errorsController = new ErrorsController();
    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
    errorsController.Execute(rc);
}

这里的如何使用错误处理程序在全球errorscontroller可能看起来像。也许我们可以定义一些自定义视图的404和500的行动:

1
2
3
4
5
6
7
8
9
10
11
12
public class ErrorsController : Controller
{
    public ActionResult Http404()
    {
        return Content("Oops 404");
    }

    public ActionResult Http500()
    {
        return Content("500, something very bad happened");
    }
}

然后我们可以订阅一个全局错误处理程序的错误,这样我们所有的Ajax不重复的错误处理代码在所有Ajax请求,但如果我们想要我们可以重复它:

1
2
3
4
$('body').ajaxError(function (evt, jqXHR) {
    var error = $.parseJSON(jqXHR.responseText);
    alert('An error occured: ' + error.errorMessage);
});

我们终于和火灾在AJAX请求到控制器的动作,我们希望将返回HTML的偏在这个案例:

1
2
3
4
5
6
$.ajax({
    url: 'whatever/trevor',
    success: function (html) {
        $container.html(html);
    }
});


创建一个修改版本的handleerrorattribute(jsonhandleerrorattribute?)[和]在您的行动jsonhandleerror JSON。

有一个看看在ASP.NET MVC handleerror ajaxauthorizeattribute [ ] [ ]与authorize jsonresult?