您可以尝试在rest服务的错误中包含异常
catch (Exception ex)
{
Log.Fatal("Could not complete process", ex);
throw new WebFaultException<string>(
string.Format(ex.Message),
HttpStatusCode.BadRequest);
}
上面的代码将处理这两种情况,假设您启用了日志记录器,您只需获取服务器上的日志文件,客户端就会收到异常消息
我想你可以给客户端发送一条友好的消息,这样他们就不会关心你的具体实现,或者创建一个你可以调用的类
WebFaultException
&T;
用。
编辑2
如果在收到请求之前遇到问题,可以尝试以下操作
向服务添加faulthandler
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class GenericErrorHandlingBehavior : Attribute, IErrorHandler, IServiceBehavior
{
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
//throw new NotImplementedException();
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
//throw new NotImplementedException();
// Adds a CoreServiceBehavior to each ChannelDispatcher
foreach (var channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
var channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(new GenericErrorHandlingBehavior());
}
}
public bool HandleError(Exception error)
{
//throw new NotImplementedException();
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
if (error is FaultException)
return;//nothing to do if the error is a fault
//the type cannot be determined[ default to this value]
var exception = new FaultException<GenericServiceFault>(
new GenericServiceFault(), new FaultReason(error.Message));
MessageFault messageFault = exception.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, exception.Action);
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
//throw new NotImplementedException();
}
}
这个
GenericServiceFault
类只是一个简单的datacontract类,
然后您可以在
ProvideFaultMethod
,或者
HandleError
方法并向用户提供有意义的错误
你可以使用
GenericErrorHandlingBehavior
将服务实现作为属性,即[genericerrorhandlingbehavior]