关于jquery:当ASP.NET异常在服务器上引发错误时,从jqXHR获取错误文本消息

Get the error text message from a jqXHR when the error was raised on the server by an ASP.NET exception

我有一个服务器端操作,如下所示:

1
2
3
4
5
6
7
8
9
10
namespace MyProduct.Presentation.Controllers
{
    public class FooController : Controller
    {
        public ActionResult Delete(long[] fooIds)
        {
            throw new Exception("Something went wrong.");
        }
    }
}

我从客户端向这个控制器发出一个ajax请求,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var url = '/Foo/Delete';

$.ajax(url,
{
  cache: false, async: false, type: 'POST',
  data: JSON.stringify({ fooIds: fooIdsArray }), dataType: 'json',
  contentType: 'application/json', traditional: true,
  error: OnError, success: OnSuccess
});

function OnSuccess(data, textStatus, jqXHR) {
  debugger;
}

function OnError(jqXHR, textStatus, errorThrown) {
  debugger;

  // Here, I want the text"Something went wrong",
  // which I set as the Message property
  // of my server side exception
}

如何将文本设置为服务器上引发的Exception对象的Message属性?

在这种情况下,客户端使用HTTP状态代码500接收HTML响应。因此,我在Fiddler中看到我的响应如下所示:

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
50
51
52
53
54
55
56
57
58
59
60
HTTP/1.1 500 Internal Server Error
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 11 Dec 2013 07:47:26 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 10175
Connection: Close

<!DOCTYPE html>
<html>
    <head>
        Could not delete category. This category has data associated with it. Please delete the associated data first.
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span>Server Error in '/' Application.<hr width=100% size=1 color=silver>

             Could not delete category. This category has data associated with it. Please delete the associated data first. </span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif">

             Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

           

             Exception Details: System.Exception: Could not delete category. This category has data associated with it. Please delete the associated data first.

            Source Error:

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <wyn>[cc]

Line 66:                 }
Line 67:
<font color=red>Line 68:                 throw new Exception(errorMessage);
</font>Line 69:             }
Line 70:             catch



源文件:C: Sathyaish Clients ESQ SVN GlobalizationUI.Presentation Controllers CategoryController.cs行:68

堆栈跟踪:






版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0.30319.18055



<! - [例外]:无法删除类别。此类别包含与之关联的数据。请先删除相关数据。 at MyProduct.Presentation.Controllers.CategoryController.Delete(Int64 [] categoryIds)in ... yada yada yada ...


您可以使用以下内容而不是抛出异常:

1
return new HttpStatusCodeResult(500,"Could not delete category. This category has data associated with it. Please delete the associated data first.");

然后,您可以从textStatus变量访问该消息。


一种方法是将服务器上的操作的返回类型更改为JsonResult,然后将方法调用包装在try catch中。 然后,这允许您在异常情况下将异常消息作为json返回:

1
2
3
4
5
6
7
8
9
10
11
12
13
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}