[JAVA] Log invisible exceptions in Jersey

Introduction

If an internal error occurs in Jersey, you will get a response with an error message at status 500, right? However, sometimes the trouble was

500 may be returned with the behavior like this, and it may be difficult to deal with it (I myself was also troubled).

jersey-500-internal-error.png

As a countermeasure in such a case, I will introduce a method to pick up the exception that occurred in Jersey and send the information to the log.

code

Set up an event listener to output information on exceptions that occurred during request / response processing to the log.

Specifically, prepare the following MyApplicationEventListener and MyRequestEventListener, and register MyApplicationEventListener of them in the application.

import org.glassfish.jersey.server.monitoring.ApplicationEvent;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;

public class MyApplicationEventListener implements ApplicationEventListener {

    @Override
    public void onEvent(ApplicationEvent event) {
    }

    @Override
    public RequestEventListener onRequest(RequestEvent event) {
        return new MyRequestEventListener();
    }
}
import java.util.logging.Logger;

import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;

public class MyRequestEventListener implements RequestEventListener {
    
    private static final Logger LOGGER = Logger.getLogger(MyRequestEventListener.class.getName());

    @Override
    public void onEvent(RequestEvent event) {
        switch (event.getType()) {
        case ON_EXCEPTION:
            LOGGER.severe(event.getException().toString());
        }
    }
}

This should log the exception information and stack trace that occurred.

Reference material

Recommended Posts

Log invisible exceptions in Jersey
Ubuntu unable to log in
Exceptions encountered in the AWS SDK
Log output to file in Java
Catch multiple exceptions together in java
Types of exceptions in business systems