Apache CXF JAX-WS return fault without logging exc

2019-07-20 11:35发布

问题:

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 here is annotated by @WebFault and extends Exception (with 2 needed constructors and getFaultInfo() method).

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.

How can I do this? Thank you.

回答1:

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);
            }
        }
    }
}

Printed log was below:

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