Redirect inside java interceptor

1.5k Views Asked by At

I would like to create interceptor for error code handling, which will redirect to proper error page in Spring MVC application. The problem is that error code comes from service, which is processed inside the request handler, so I probably need to intercept the service not the request handler. For example:

@RequestMapping(value = "/products", method = RequestMethod.GET)
public ModelAndView handleProducts(ModelAndView mav) {
        //do something
        ...
        //load products
        ResponseMo response = productsService.getProducts();
        //process the response
        mav.addObject("products", response.getData());
        ...
        /do something else
        return mav;
}

What I need is to catch the response of getProducts() and if there is error response, I need to redirect... In the project, there are many such handlers and service calls, so I need to solve it on one place. ProductsService is part of the project, same ear. I was thinking about interceptors, filters, aspects... I can intercept the getProducts() call, but I cannot redirect inside the interceptor, or can I? Or should I use some different approach?

1

There are 1 best solutions below

5
On

see https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Create custom exceptions that will fit into your business cases, then handle the exceptions in the controller. Hope it helps.