[英]Exception handling in ASP.NET (C#) web services
我一直在尋找一種將我的asp.net應用程序的Web服務中的異常消息傳輸到ajax錯誤回調函數的方法。 我所能找到的只是將Web服務引發的異常捕獲到C#代碼中,但是我從ajax代碼而不是C#代碼調用服務。 除了返回HTTP狀態代碼外,我還需要其他東西。
這是我的服務代碼的catch塊:
catch (Exception ex)
{
var fault = new GenericFault { Message = ex.Message, Operation = "" };
throw new FaultException<GenericFault>(fault);
}
}
這是我的ajax錯誤回調:
error: function (err) {
alert("The server encountered an error, please resubmit your request. If the problem persists, contact your administrator.");
return 'error occured';
}
我已經嘗試拋出Web錯誤異常,但是由於僅傳遞HTTP狀態代碼,因此也沒有達到目的。
找到了答案。 訣竅在於拋出正確的異常。
由於在回調錯誤函數中捕獲的錯誤會在xhr對象中看到詳細信息。
因此,您需要拋出帶有狀態碼和字符串消息的HttpException。 catch塊應類似於:
catch (Exception ex)
{
throw new HttpException(500, ex.Message);
}
那么您的ajax回調將獲得您從此處傳遞的ex.message:
error: function (err) {
alert("The Detailed server error is "+err.responseJSON.Message);
return 'error occured';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.