簡體   English   中英

從Ajax調用中檢索服務器端錯誤詳細信息(C#)

[英]Retrieving server side error details (c#) from an ajax call

當我的應用程序進行ajax調用時,我拋出一個錯誤,並希望在我的客戶端捕獲它。 哪種方法是最好的。

我的服務器端代碼是:

try
{
     ...
}
catch (Exception ex)
{
     throw new HttpException("This is my error", ex);
}

我的客戶端代碼是:

var url = $(this).attr('href');
var dialog = $('<div style="display:none"></div>').appendTo('body');

dialog.load(url, {}, 
    function (responseText, status, XMLHttpRequest) {

            if (status == "error") {
                alert("Sorry but there was an error: " + XMLHttpRequest.status + " " + XMLHttpRequest.statusText);
                return false;
            }
            ....

在運行時,調試時,我沒有得到我的錯誤詳細信息,如下面的屏幕截圖所示:

在此處輸入圖片說明

我收到一般錯誤:

status: 500
statusText: Internal Server Error

如何獲得發送的詳細信息:“這是我的錯誤”?

最后我使用這種方法:

Web.config文件:

<system.web>
  <customErrors mode="On" defaultRedirect="~/error/Global">
    <error statusCode="404" redirect="~/error/FileNotFound"/>
  </customErrors>
</system.web>

ErrorController:

public class ErrorController : Controller
{
    public ActionResult Global()
    {
        return View("Global", ViewData.Model);
    }
    public ActionResult FileNotFound()
    {
        return View("FileNotFound", ViewData.Model);
    }
}

不要忘記創建2個特定視圖。

最后,當我需要拋出特定的錯誤代碼和描述時,我將像這樣進行操作:

    public ActionResult MyAction()
    {
        try
        {
            ...
        }
        catch
        {
            ControllerContext.RequestContext.HttpContext.Response.StatusCode = 500;
            ControllerContext.RequestContext.HttpContext.Response.StatusDescription = "My error message here";
            return null;
        }
    }

然后,客戶端會收到此類錯誤信息。

做這樣的事情

服務器端:

try{
 //to try
}catch(Exception ex)
{
    return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error :"+ ex.Message);
}

然后,該請求將向JavaScript返回錯誤500,但帶有您的異常消息。

您可以控制發送給客戶端的詳細錯誤消息。 默認情況下,只有通過從服務器本身瀏覽站點才能查看詳細的錯誤消息。

要以這種方式從服務器端顯示自定義錯誤,您需要在IIS configuration添加規則。

您可以閱讀此主題,也許可以為您提供幫助: 如何在從客戶端瀏覽器瀏覽時啟用網站的詳細錯誤消息?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM