handling wrapped exceptions in spring mvc

前端 未结 3 1246
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 11:47

I have Spring MVC and jackson. When I start an incorrect request, Jackson mapping fails and UnrecognizedPropertyException is thrown. I want to handle this excep

相关标签:
3条回答
  • 2020-12-06 12:15

    Unfortunately, UnrecognizedPropertyException is a subtype of IOException. The RequestResponseBodyMethodProcessor that handles the @RequestBody (I assume that's where the exception occurs) has special handling for IOException (interpreting as a failure of the request input stream), wrapping it in a HttpMessageNotReadableException. Additionally, the HttpMessageConverter interface is specified to throw HttpMessageNotReadableException if there is a conversion error during read.

    You're going to have to deal with that no matter what (if Jackson threw unchecked exceptions instead, things might have been different).

    Fortunately, since 4.3, Spring MVC's ExceptionHandlerMethodResolver (which processes @ExceptionHandler) can unwrap the cause of exceptions (see SPR-14291). As such, assuming you do not have a handler for any exceptions in the inheritance hierarchy of HttpMessageNotReadableException, your handler method

    @ExceptionHandler
    public String handle(UnrecognizedPropertyException e) {
        ...
    }
    

    will be used to handle the exception. This happens after Spring MVC looks for a handler method that could handle a HttpMessageNotReadableException, then unwraps the nested exception with Throwable#getCause and tries the lookup again.


    In pre-4.3, or if you do have a handler for an exception type in HttpMessageNotReadableException's inheritance hierarchy, you can always delegate after extracting the cause yourself.

    @ExceptionHandler
    public String handle(HttpMessageConversionException e) throws Throwable {
        Throwable cause = e.getCause();
        if (cause instanceof UnrecognizedPropertyException) {
            handle((UnrecognizedPropertyException) cause);
        }
        ...
    }
    
    public String handle(UnrecognizedPropertyException e) {
        ...
    }
    
    0 讨论(0)
  • 2020-12-06 12:21

    I do it this way:

    /**
     * Global exception handler for unhandled errors.
     * @author Varun Achar
     * @since 2.0
     * @version 1.0
     *
     */
    public class Http500ExceptionResolver extends SimpleMappingExceptionResolver
    {
        @Inject
        private ViewResolver resolver;
    
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        {
            ModelAndView mv = new ModelAndView();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            if(CommonUtil.isAjax(request))
            {
                MappingJackson2JsonView view = new MappingJackson2JsonView();
                view.setObjectMapper(JsonUtil.getObjectMapper());
                mv.addObject("responseMessage", "We had some problems while serving your request. We are looking into it");
                mv.addObject("responseCode", GenericResponse.ERROR.code());
                mv.addObject("success", false);
                mv.setView(view);
            }
            else
            {
                mv.setViewName(resolver.getView(ViewConstants.ERROR_PAGE));
            }
            return mv;
        }
    }
    

    And in my servlet-context :

       <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
            <property name="order" value="0" />
        </bean>
        <bean id="securityExceptionResolver"
            class="com.trelta.commons.utils.security.SecurityExceptionResolver">
            <property name="order" value="1"></property>
            <property name="exceptionMappings">
                <map>
                    <entry key="org.springframework.security.access.AccessDeniedException"
                        value="/common/accessDenied"></entry>
                    <entry key="org.springframework.security.core.AuthenticationException"
                        value="/common/authenticationFailure"></entry>
                </map>
            </property>
        </bean>
        <bean id="http500ExceptionResolver"
                class="com.trelta.commons.utils.security.Http500ExceptionResolver">
                <property name="order" value="3" />
        </bean>
    

    The order field is important since Spring cycles through the exception resolvers in that order. You can also define an exception mapping of this sort for yourself and you're good to go!

    Check this blog post and javadoc for SimpleMappingExceptionResolver

    0 讨论(0)
  • 2020-12-06 12:29

    We are using org.apache.commons.lang.exception.ExceptionUtils ...

    private myMethod (Throwable t) {
    
        if (ExceptionUtils.getRootCause(t) instanceof MyException) ...
    }
    
    0 讨论(0)
提交回复
热议问题