Home > database >  Adding interceptor for success API response
Adding interceptor for success API response

Time:04-29

I have a Spring application where I want to log the user operation into a database table. E.g. if the user has called a POST createBook API, then I want to log this create action into a table.

I intend to use the Spring HandlerInterceptorAdapter and to override the afterCompletion method.

My questions:

  1. If exception is thrown inside the API, will the afterCompletion method also be called? Is there any way to intercept only if no exception is thrown and it is a success response.

  2. There are only some specific set of APIs I want to intercept. Is there any elegant way to do other than checking the API path inside the method ?

public class OperationInterceptor extends HandlerInterceptorAdapter {
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {
        if ("/book".equals(request.getServletPath() && "POST".equals(request.getMethod())) {
            //log the operation into db
        }

        if ("/order".equals(request.getServletPath() && "POST".equals(request.getMethod())) {
            //log the operation into db
        }
    }
}

CodePudding user response:

You can add if condition like this inside afterCompletion method.

if(ex!=null){
   Stream.of(
            new String[]{"/book", "POST"},
            new String[]{"/order", "GET"})
            .filter((p)-> Objects.equals(request.getServletPath(),p[0])&&Objects.equals(request.getMethod(),p[1]))
            .findAny().ifPresent(r->{
            System.out.println("//log oprations");
    });
}
  • Related