本文介绍了Apache CXF JAX-WS返回错误,没有记录异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Apache CXF返回错误的SOAP消息,但是我发现它的唯一方法是自定义异常( @WebFault )。例如(这是我的 @WebService 的方法):

I'm trying to return fault SOAP-message with Apache CXF, but only one way I could find it is custom exceptions (@WebFault). For example (this is my @WebService's method):

@Override
public String getAuthKey(String username, String password) throws BadCredeintialsException {
    UserDetails ud = userDetailsService.loadUserByUsername(username);
    String pwd = passwordEncoder.encode(password);

    if (pwd.equals(ud.getPassword())) {
        return authKeyService.generateAuthKey(ud.getUsername()).getKey();
    }
    else {
        throw new BadCredeintialsException("Wrong username or password", new FaultInfoBean());
    }
}

BadCredeintialsException 在此处由 @WebFault 注释,并且扩展了异常(带有2个所需的构造函数和 getpaultInfo()方法)。

BadCredeintialsException here is annotated by @WebFault and extends Exception (with 2 needed constructors and getFaultInfo() method).

问题:当引发异常时,服务器将异常的堆栈跟踪记录打印到日志中,但是我不需要这个,这种情况(错误的登录名或密码)对于我的服务器日志来说太低了,我只需要以SOAP消息的形式返回错误,不需要抛出真正的异常。

Problem: When exception throws, server prints stack trace of exception into log, but I don't need this, this case (wrong login or pwd) is too low for garbage my server log, I need just return fault as SOAP-message, don't need to throw a real exception.

我该怎么做?谢谢。

推荐答案

我通过定义FaultHandler拦截器来解决此问题,并将异常标记为已知的预期异常。在这种情况下,CXF不会打印 WARN 和异常跟踪。

I worked around this by defining a FaultHandler Interceptor, and mark exception as known, expected exception. In this case CXF didn't print WARN and exception trace.

@Override
public void handleFault(Message message) {

    FaultMode mode = message.get(FaultMode.class);
    Exception exception = message.getContent(Exception.class);

    if (exception != null && exception.getCause() != null) {
        if (mode != FaultMode.CHECKED_APPLICATION_FAULT) {
            if (exception.getCause() instanceof NotificationFailedException) {
                message.put(FaultMode.class, FaultMode.CHECKED_APPLICATION_FAULT);
            }
        }
    }
}

已打印日志如下:

INFO    Application {http:<url>}NotificationListener#{http://<url>}Notify has thrown exception, unwinding now: NotificationFailedException: Strange Error

这篇关于Apache CXF JAX-WS返回错误,没有记录异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 00:35