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

 爱中华爱美丽 发布于 2023-02-11 15:58

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

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
}

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

在这种情况下,客户端使用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



    
        Could not delete category. This category has data associated with it. Please delete the associated data first.
        
    

    

            

Server Error in '/' Application.

Could not delete category. This category has data associated with it. Please delete the associated data first.

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:


Line 66:                 }
Line 67: 
Line 68:                 throw new Exception(errorMessage);
Line 69:             }
Line 70:             catch

Source File: C:\Sathyaish\Clients\ESQ\SVN\GlobalizationUI.Presentation\Controllers\CategoryController.cs    Line: 68

Stack Trace:


[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



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18055