我正在开发一个分布式应用程序。其中有一些角色和权限集需要我进行验证。
在这种情况下,向客户端发送一条错误信息,比如未授权访问是否是个好的做法?
还是应该抛出一个异常?
我正在开发一个分布式应用程序。其中有一些角色和权限集需要我进行验证。
在这种情况下,向客户端发送一条错误信息,比如未授权访问是否是个好的做法?
还是应该抛出一个异常?
在您的服务操作中,您可以指定一个FaultContract,它将同时用于以下两个目的:
[OperationContract]
[FaultContract(typeof(MyServiceFault))]
void MyServiceOperation();
请注意,MyServiceFault 必须使用 DataContract 和 DataMember 属性进行标记,就像你处理复杂类型时一样:
[DataContract]
public class MyServiceFault
{
private string _message;
public MyServiceFault(string message)
{
_message = message;
}
[DataMember]
public string Message { get { return _message; } set { _message = value; } }
}
在服务端,您可以:
throw new FaultException<MyServiceFault>(new MyServiceFault("Unauthorized Access"));
并且在客户端:
try
{
...
}
catch (FaultException<MyServiceFault> fault)
{
// fault.Detail.Message contains "Unauthorized Access"
}
在WCF服务实现方法中,您可以捕获所有异常并将它们重新抛出为FaultExceptions。通过这种方式,异常将会在客户端上重新抛出,并且您可以选择自己的消息作为提示:
[OperationContract]
public List<Customer> GetAllCustomers()
{
try
{
... code to retrieve customers from datastore
}
catch (Exception ex)
{
// Log the exception including stacktrace
_log.Error(ex.ToString());
// No stacktrace to client, just message...
throw new FaultException(ex.Message);
}
}
public List<Customer> GetAllCustomers()
{
try
{
... code to retrieve customers from datastore
}
catch (MyBaseException ex)
{
// This is an error thrown in code, don't bother logging it but relay
// the message to the client.
throw new FaultException(ex.Message);
}
catch (Exception ex)
{
// This is an unexpected error, we need log details for debugging
_log.Error(ex.ToString());
// and we don't want to reveal any details to the client
throw new FaultException("Server processing error!");
}
}
如果您不使用 basicHTTPBinding,抛出一般的Dot Net异常会导致服务客户端代理和服务器通道进入故障状态...为避免这种情况,您应该始终从服务中抛出 FaultException...
只需在您的 catch 块中使用:
throw new FaultException("Your message to the clients");