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

Jquery 当ASP.NET异常在服务器上引发错误时,从jqXHR获取错误文本消息,jquery,asp.net,asp.net-mvc,asp.net-mvc-4,Jquery,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我有一个服务器端操作,如下所示: namespace MyProduct.Presentation.Controllers { public class FooController : Controller { public ActionResult Delete(long[] fooIds) { throw new Exception("Something went wrong."); } } }

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

namespace MyProduct.Presentation.Controllers
{
    public class FooController : Controller
    {
        public ActionResult Delete(long[] fooIds)
        {
            throw new Exception("Something went wrong.");
        }
    }
}
我从客户端向该控制器发出ajax请求,如下所示:

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
}
如何将在服务器上引发的
异常
对象的
消息
属性设置为文本

return new HttpStatusCodeResult(500, "Could not delete category. This category has data associated with it. Please delete the associated data first.");
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}
在这种情况下,客户机接收HTTP状态代码为500的HTML响应。所以,我在Fiddler中看到我的回答是这样的:

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>
        <title>Could not delete category. This category has data associated with it. Please delete the associated data first.</title>
        <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><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

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

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

            <b> Description: </b>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.

            <br><br>

            <b> Exception Details: </b>System.Exception: Could not delete category. This category has data associated with it. Please delete the associated data first.<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

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

                  </td>
               </tr>
            </table>

            <br>

            <b> Source File: </b> C:\Sathyaish\Clients\ESQ\SVN\GlobalizationUI.Presentation\Controllers\CategoryController.cs<b> &nbsp;&nbsp; Line: </b> 68
            <br><br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[Exception: Could not delete category. This category has data associated with it. Please delete the associated data first.]
   MyProduct.Presentation.Controllers.CategoryController.Delete(Int64[] categoryIds) in yada yada yada

</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18055

            </font>

    </body>
</html>
<!-- 
[Exception]: Could not delete category. This category has data associated with it. Please delete the associated data first.
   at MyProduct.Presentation.Controllers.CategoryController.Delete(Int64[] categoryIds) in ...yada yada yada...
HTTP/1.1500内部服务器错误
return new HttpStatusCodeResult(500, "Could not delete category. This category has data associated with it. Please delete the associated data first.");
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}
服务器:ASP.NET开发服务器/10.0.0.0 日期:2013年12月11日星期三格林尼治标准时间07:47:26 X-AspNet-Version:4.0.30319 缓存控制:专用 内容类型:text/html;字符集=utf-8 内容长度:10175 连接:关闭 无法删除类别。此类别具有与其关联的数据。请先删除关联的数据。 正文{字体系列:“Verdana”;字体重量:正常;字体大小:.7em;颜色:黑色;} p{字体系列:“Verdana”;字体大小:正常;颜色:黑色;页边顶部:-5px} {字体系列:“Verdana”;字体大小:粗体;颜色:黑色;页边顶部:-5px} H1{字体系列:“Verdana”;字体重量:正常;字体大小:18pt;颜色:红色} H2{字体系列:“Verdana”;字体重量:正常;字体大小:14pt;颜色:褐红色} 前{字体系列:“控制台”,“Lucida控制台”,单空格;字体大小:11pt;边距:0;填充:0.5em;线条高度:14pt} .marker{字体大小:粗体;颜色:黑色;文本装饰:无;} .version{color:gray;} .错误{页边距底部:10px;} .expandable{文本装饰:下划线;字体大小:粗体;颜色:海军蓝;光标:手;} @媒体屏幕和屏幕(最大宽度:639px){ pre{width:440px;溢出:自动;空白:预换行;换行:断开单词;} } @媒体屏幕和屏幕(最大宽度:479px){ 前{宽度:280px;} } “/”应用程序中出现服务器错误。
无法删除类别。此类别具有与其关联的数据。请先删除关联的数据。 描述:执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源。

异常详细信息:系统。异常:无法删除类别。此类别具有与其关联的数据。请先删除关联的数据。

源错误:


return new HttpStatusCodeResult(500, "Could not delete category. This category has data associated with it. Please delete the associated data first.");
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}
第66行:} 第67行: 第68行:抛出新异常(errorMessage); 第69行:} 第70行:捕获

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

堆栈跟踪:


return new HttpStatusCodeResult(500, "Could not delete category. This category has data associated with it. Please delete the associated data first.");
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}
[例外:无法删除类别。此类别具有与其关联的数据。请先删除关联的数据。] yada yada中的MyProduct.Presentation.Controller.CategoryController.Delete(Int64[]CategoryId)

版本信息:Microsoft.NET Framework版本:4.0.30319;ASP.NET版本:4.0.30319.18055
您可以使用以下选项,而不是引发异常:


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

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

return new HttpStatusCodeResult(500, "Could not delete category. This category has data associated with it. Please delete the associated data first.");
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}

可能重复。@Zabavsky:我对如何解决处理错误情况的一般问题并不感兴趣。我对处理ASP.NET引发的异常的其他方法也不感兴趣。我知道所有的选择。我只是想知道序列化异常在jQuery XHR对象中会转换成什么。似乎XHR并不关心返回的响应的细节,在本例中,正好是一个HTML DOM,我感兴趣的值被嵌入到DOM中,我不想编写DOM解析例程来获取该值。如果您编写
try catch
,那么在ajax中,每次都会调用
OnSuccess
方法<永远不会调用code>OnError
方法您可以通过向返回的json对象添加一个success布尔参数来解决此问题。然后,您可以在javascript中检查success参数是true还是false,如果它等于false,则写出异常。另一个选项是使用标准控制器,这样您的操作可以返回一个HttpResponseMessage,您可以在其中手动设置响应代码并在响应正文中返回异常。这一点很好。我知道所有的选择。我只是想知道序列化异常在jQuery XHR对象中会转换成什么。似乎XHR并不关心返回的响应的细节,在本例中,它恰好是一个HTML DOM,我感兴趣的值嵌入到DOM中,我不想编写DOM解析例程来获取该值。这一点很好。我知道所有的选择。我只是想知道序列化异常在jQuery XHR对象中会转换成什么。似乎XHR并不关心返回的响应的细节,在本例中,它恰好是一个HTML DOM,我感兴趣的值嵌入到DOM中,我不想编写DOM解析
return new HttpStatusCodeResult(500, "Could not delete category. This category has data associated with it. Please delete the associated data first.");
public JsonResult Delete(long[] fooIds)
{
    try
    {
        //make method calls
        return Json(new {});
    }
    catch(Exception ex)
    {
         return Json(new {exception = ex.message});
    }

}