Spring Exception Handling - How to Use ExceptionResolver and @ExceptionHandler at the Same Time

I developed a web application in which form validation exceptions should be handled by @ExceptionHandler (must be flexible), and general system exceptions should be handled by SimpleMappingExceptionResolver (things like email notification, etc.).

The problem is that if I use both, the exceptions that are displayed for @ExceptionHandler do not fall into @ExceptionHandler, but are caught by ExceptionResolver as defaultError.

Any idea what needs to be done to get this working together?

@ExceptionHandler(ValidatorException.class)
public String handleFormException(ValidatorException ex, ActionRequest actionRequest) {
    logger.error(ex.getMessage());
    //TODO make conditions
    return "mainOrderForm";
}

@ActionMapping(params = "action=addDocOrder")
public void addDocOrder(@ModelAttribute("order") CstOrderBeanImpl orderBean,
        BindingResult result, ActionRequest actionRequest, ActionResponse response) 
        throws PortalException, SystemException, ValidatorException {
    logger.info("Adding Form Order");
    Calendar cal = TimeUtils.getEuDeadLine(orderBean);
    orderBean.setDeadLine(cal.getTime());
    ValidatorException ve = validateService.validate(orderBean, result, actionRequest, validator);
    if (ve != null) throw ve;
(...)

There is a DispatcherPortlet in

catch (Exception ex) {
    // Trigger after-completion for thrown exception.
    triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
(...)

Which checks for interceptors, but none exists, so it does by default ...

, , ""... ..

+3
3

, ExceptionResolver .

public ModelAndView resolveException(RenderRequest req, RenderResponse res, Object handler,Exception exc) {
    if(exc instanceof ValidatorException) {
        try {
            java.lang.reflect.Method m = handler.getClass().getMethod("someMethod", (Class<?>)null /* method parameters? */);
            m.invoke(handler,new Object[]{(ValidatorException)exc,req/*, res - maybe?*/});
        } catch(Exception e) {
            // Handle exception
        }
    }

    // Send email of the error etc..
}

, .

+2

Exception Resolver app-context, DispatcherServlet ( AnnotationMethodHandlerExceptionResolver ).

AnnotationMethodHandlerExceptionResolver SimpleMappingExceptionResolver, .

. .

+2

I am not familiar with the Portlet environment, but maybe you also need to declare AnnotationMethodHandlerExceptionResolver.

0
source

Source: https://habr.com/ru/post/1776352/


All Articles