Jersey: How to register a ExceptionMapper that omits some subclasses? - jersey

How do I register a catch-all ExceptionMapper<Exception> that does not intercept WebApplicationException for which Jersey provides special handling?
UPDATE: I filed this feature request: http://java.net/jira/browse/JERSEY-1607

I ended up registering a ExceptionMapper:
import com.google.inject.Singleton;
import com.sun.jersey.api.container.MappableContainerException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* #author Gili Tzabari
*/
#Provider
#Singleton
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException>
{
#Override
public Response toResponse(RuntimeException e)
{
if (e instanceof WebApplicationException)
{
// WORKAROUND: Attempt to mirror Jersey's built-in behavior.
// #see http://java.net/jira/browse/JERSEY-1607
WebApplicationException webApplicationException = (WebApplicationException) e;
return webApplicationException.getResponse();
}
// Jetty generates a log entry whenever an exception is thrown. If we don't register an
// ExceptionMapper, Jersey will log the exception a second time.
throw new MappableContainerException(e);
}
}

Take a look how it's done in ReXSL ExceptionTrap class. You don't register an ExceptionMapper to catch all exception un-caught by Jersey. Instead, you let them bubble up to the Servlet container (e.g. Tomcat), and the container will forward them to the right servlet for further handling.
The main and only purpose of ExceptionMapper is to convert certain business-specific exceptions to HTTP responses. In other words, let the application control exceptional flow of events. On the other hand, the purpose of servlet exception catching mechanism is to control application failover and do some post-mortem operations, like, for example, logging. In other words, ExceptionMapper works when you're still in control, while exception catching servlet helps when control is lost and you have to show 50x response code to the user.
Jetty logs (through JUL) every WebApplicationException if status code of its encapsulated Response is higher than 500. Runtime exceptions are not logged by Jetty, they just bubble up to the container.

Extend ExtendedExceptionMapper and implement isMappable(e):
#Override
public boolean isMappable(T e) {
return !e instanceof WebApplicationException;
}

Related

How to throw exception from Spring AOP declarative retry methods?

I'm implementing some retry handling in my methods using Spring Retry.
I have a Data Access Layer (DAL) in my application and a Service Layer in my application.
My Service layer calls the DAL to make a remote connection to retrieve information. If the DAL fails it will retry. However, if the number of retries fails I would like to rethrow an exception.
In my current project I something very similar to this:
#Configuration
#EnableRetry
public class Application {
#Bean
public Service service() {
return new Service();
}
}
#Service
class Service {
#Autowired
DataAccessLayer dal;
public void doSomethingWithFoo() {
Foo foo = dal.getFoo()
// do something with Foo
}
}
#Service
class DataAccessLayer {
#Retryable(RemoteAccessException.class)
public Foo getFoo() {
// call remote HTTP service to get Foo
}
#Recover
public Foo recover(RemoteAccessException e) {
// log the error?
// how to rethrow such that DataAccessLayer.getFoo() shows it throws an exception as well?
}
}
My Application has a Service and the Service calls DataAccessLayer getFoo. If getFoo fails a number of times the DAL will handle the retries. If it fail's after that I'd like my Service layer to do something about it. However I'm not sure how to let that be known. I'm using intelliJ and when I try to throw e; in the #Recover recover method I don't get any warnings that DataAccessLayer.getFoo throws any exceptions. I'm not sure if it will. But I'd like the IDE to warn me that when the retries fail a new exception will be thrown to let the Service layer know to expect it. Otherwise if it calls dal.getFoo it doesn't know to handle any errors. How is this typically handled? Should I not use the AOP declarative style and go for imperative?
You can change getFoo() (and recover()) to add throws <some checked exception> and wrap the RemoteAccessException in it (in recover()).
That will force the service layer to catch that exception.

How can I make the MDC available during logging in a spring controller advice?

I have a spring-boot web application which makes use of logback's MDC context to enrich the log with custom data. I have the following implementation in place which makes available some custom data associated with "customKey" and it properly gets logged after adding %X{customKey} to the logging pattern in the logback configuration:
public class MDCFilter extends OncePerRequestFilter implements Ordered {
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
try {
MDC.put("customKey", "someValue");
filterChain.doFilter(httpServletRequest, httpServletResponse);
} catch(Throwable t) {
LOG.error("Uncaught exception occurred", t);
throw t;
} finally {
MDC.remove("customKey");
}
}
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE - 4;
}
}
This works fine as long as no uncaught exceptions are being thrown. To handle these I have a controller advice in place. Sadly the MDC is not available during logging in the controller advice anymore since it has already been cleaned up. If I understand correctly spring determines the responsible ExceptionHandler by using the HandlerExceptionResolverComposite - implementation which registers itself with the lowest precedence - hence it comes last after the MDC has already been cleaned up.
My qurestion now is: How should I register my filter so that the MDC is still available during logging in the controller advice?
I think one option would be to remove the MDC.remove(...) call from the finally block of the filter and instead implement a ServletRequestListener which does the cleanup of the MDC in the requestDestroyed - method. But since the filter is used in multiple web modules I would need to make sure that the ServletRequestListener is also declared in every existing and prospective module along with the MDCFilter which seems kind of error-prone to me. Moreover I would prefer it if the filter responsible for adding data to the MDC also takes care of its removal.

Modify Feign log behavior for specific exceptions

I have a spring controller that returns a custom-made exception.
However, I don't want that specific exception to cause a "Log.Error()"
Unfortunately, Feign logs it that way automatically.
Is there any way to change this behavior?
Thanks.
Apparently, it wasn't Feign that was the problem, but the embedded Tomcat that did the log writing.
We were able to add a "TurboFilter" to the Logger to prevent that specific exception from making its' way to our logs:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
// o.a.c.c.C is the name of the Apache Tomcat logger
Logger root = (Logger) LoggerFactory.getLogger("o.a.c.c.C");
root.getLoggerContext().addTurboFilter(new TurboFilter() {
#Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
if(null != t && t instanceof OurCustomException) {
return FilterReply.DENY;
}
return FilterReply.ACCEPT;
}
});

Handling exceptions in Spring MVC along with Rest API

I am using #ControllerAdvice annotation for defining exceptions at application level. Now the problem is I am having two #ControllerAdvice classes, one for REST and one for the normal web app. When I define #ExceptionHandler for Exception.class in both, only the first one is considered. How do I separate both? Or how can I catch an Exception and determine from where it has occured? Is there a way or else do I need to use controller-specific exception handlers?
I resolved this issue by creating a custom exceptions for my application and giving one exception handler method for each of them with #exception handler.
I also used aspects to make sure that every exception is converted to any of the custom exceptions.
#Aspect
#Component
public class ExceptionInterceptor {
#AfterThrowing(pointcut = "within(x.y.package..*)", throwing = "t")
public void toRuntimeException(Throwable t)
throws ApplicationException1, ApplicationException2,ApplicationException3 {
if (t instanceof ApplicationException1) {
throw (ApplicationException1) t;
} else if (t instanceof ApplicationException2) {
throw (ApplicationException2) t;
} else
throw (ApplicationException3) t;
}
}
These will transfer control to #controlleradvice.
I noticed this have been left for a month or so, so it might be old. But this article may help http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/.
The section 3.5 is probably what you are looking for, a custom Exception Resolver.

Server-side schema validation with JAX-WS

I have JAX-WS container-less service (published via Endpoint.publish() right from main() method). I want my service to validate input messages. I have tried following annotation: #SchemaValidation(handler=MyErrorHandler.class) and implemented an appropriate class. When I start the service, I get the following:
Exception in thread "main" javax.xml.ws.WebServiceException:
Annotation #com.sun.xml.internal.ws.developer.SchemaValidation(outbound=true,
inbound=true, handler=class mypackage.MyErrorHandler) is not recognizable,
atleast one constructor of class
com.sun.xml.internal.ws.developer.SchemaValidationFeature
should be marked with #FeatureConstructor
I have found few solutions on the internet, all of them imply the use of WebLogic container. I can't use container in my case, I need embedded service. Can I still use schema validation?
The #SchemaValidation annotation is not defined in the JAX-WS spec, but validation is left open. This means you need something more than only the classes in the jdk.
As long as you are able to add some jars to your classpath, you can set this up pretty easily using metro (which is also included in WebLogic. This is why you find solutions that use WebLogic as container.). To be more precise, you need to add two jars to your classpath. I'd suggest to
download the most recent metro release.
Unzip it somewhere.
Add the jaxb-api.jar and jaxws-api.jar to your classpath. You can do this for example by putting them into the JAVA_HOME/lib/endorsed or by manually adding them to your project. This largely depends on the IDE or whatever you are using.
Once you have done this, your MyErrorHandler should work even if it is deployed via Endpoint.publish(). At least I have this setup locally and it compiles and works.
If you are not able to modify your classpath and need validation, you will have to validate the request manually using JAXB.
Old question, but I solved the problem using the correct package and minimal configuration, as well using only provided services from WebLogic. I was hitting the same problem as you.
Just make sure you use correct java type as I described here.
As I am planning to expand to a tracking mechanism I also implemented the custom error handler.
Web Service with custom validation handler
import com.sun.xml.ws.developer.SchemaValidation;
#Stateless
#WebService(portName="ValidatedService")
#SchemaValidation(handler=MyValidator.class)
public class ValidatedService {
public ValidatedResponse operation(#WebParam(name = "ValidatedRequest") ValidatedRequest request) {
/* do business logic */
return response;
}
}
Custom Handler to log and store error in database
public class MyValidator extends ValidationErrorHandler{
private static java.util.logging.Logger log = LoggingHelper.getServerLogger();
#Override
public void warning(SAXParseException exception) throws SAXException {
handleException(exception);
}
#Override
public void error(SAXParseException exception) throws SAXException {
handleException(exception);
}
#Override
public void fatalError(SAXParseException exception) throws SAXException {
handleException(exception);
}
private void handleException(SAXParseException e) throws SAXException {
log.log(Level.SEVERE, "Validation error", e);
// Record in database for tracking etc
throw e;
}
}

Resources