是的,你可以實現IErrorHandler
並用它來映射異常。您不需要從業務邏輯中拋出WebFaultException
,只需拋出自定義異常。
例如,您可以將YourCustomException
映射到一些簡單的json字符串。你可以放置一些對象而不是字符串。樣品IErrorHandler.ProvideFault
實現:
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
if (error is YourCustomException)
{
fault = Message.CreateMessage(version, string.Empty, String.Format("Error: {0}.", error.Message), new DataContractJsonSerializer(typeof(string)));
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.InternalServerError);
}
}
所以當YourCustomException
是業務邏輯拋出,將被處理程序獲取,並轉換成正確的故障。
另請參閱:CodeProject article