简体   繁体   English

Java Web服务和远程异常的最佳实践

[英]Best practice for java web services and remote exception

I am writing a web service. 我正在写一个Web服务。 So I have: 所以我有:

public interface MyService extends Remote
{
  public void service1();
}

public class MyServiceImpl implements MyService
{
  public void service1() { /* do something that sometimes throws an exception */ }
}

I was reading about RemoteException . 我正在阅读有关RemoteException Should I wrap all the code in service1() in a try..catch that wraps any exception in a RemoteException ? 我是否应该将try..catch中的所有代码都包装在service1()中,以将任何异常包装在RemoteException Then I will have to do it for service2() , service3() and so on. 然后,我将不得不这样做对service2() service3()等。

Is it better to let the invoker (a servlet in my case) to do this? 最好让调用程序(在我的例子中为servlet)执行此操作?

What exactly should be wrapped in remote exception - everything that happens in the server? 在远程异常中究竟应该包含什么内容-服务器中发生的一切? or only exceptions dealing with the remote invocation process (reflection, serialization, etc)? 还是仅涉及远程调用过程(反射,序列化等)的异常?

Your code shouldn't be throwing RemoteException , it should be reserved for the WS framework if and when errors occur accessing the remote service. 您的代码不应RemoteException ,如果在访问远程服务时发生错误,则应将其保留给WS框架。

Most of the frameworks will catch Exception , wrap it up as a SOAP-Fault, which is the client deals with normally by throwing another exception with the error message from the SOAP-Fault (remember the client may not be Java). 大多数框架都将捕获Exception ,并将其包装为SOAP-Fault,这是客户端通过处理来自SOAP-Fault的错误消息引发的另一个异常来正常处理的(请记住,客户端可能不是Java)。

The up-shot of this is you should throw exceptions specific to the fault that has occurred, leaving the framework to send the appropriate response. 这样做的结果是,您应该引发特定于已发生故障的异常,使框架发送适当的响应。

As far as I know you only need to declare that the methods throw RemoteException in the interface. 据我所知,您只需要声明该方法在接口中引发RemoteException

public interface MyService extends Remote {
  public void service1() throws RemoteException;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM