是的,你可以实现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