Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: SimpleMappingExceptionResolver together with @ExceptionHandler?

I like SimpleMappingExceptionResolver, because in one place i have all exception->view mappings for all controllers in web-app (i suppose that). To customize some exception in specific controller i would like to use @ExceptionHandler, but it doesn't work together - all exceptions are handled by SimpleMappingExceptionResolver. How to make this work together ?

@Controller
public class SomeController {
    ...

    @ExceptionHandler(SomeException.class)
    public ModelAndView handleException(Exception ex) {
         // ...
    }   

}

SimpleMappingExceptionResolver:

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="defaultErrorView" value="error"/>
    <property name="exceptionMappings">
        ...
    </property>
</bean> 
like image 562
marioosh Avatar asked Jun 14 '11 12:06

marioosh


People also ask

Why do you extend SimpleMappingExceptionResolver?

SimpleMappingExceptionResolver is an implementation of HandlerExceptionResolver. It allows us to configure following parameters: mapping exception class names to view names. mapping view names to response status codes.

What is the difference between ControllerAdvice and RestControllerAdvice?

The differences between @RestControllerAdvice and @ControllerAdvice is : @RestControllerAdvice = @ControllerAdvice + @ResponseBody . - we can use in REST web services. @ControllerAdvice - We can use in both MVC and Rest web services, need to provide the ResponseBody if we use this in Rest web services.

What is true about the @ExceptionHandler and @ControllerAdvice annotations?

The@ControllerAdvice annotation allows us to consolidate our multiple, scattered @ExceptionHandlers from before into a single, global error handling component. The actual mechanism is extremely simple but also very flexible: It gives us full control over the body of the response as well as the status code.

How does Spring handle global exception?

Global Exception Handler - Exception Handling is a cross-cutting concern, it should be done for all the pointcuts in our application. We have already looked into Spring AOP and that's why Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.


1 Answers

Short answer: p:order

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" p:order="1" />
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:order="2" p:defaultErrorView="uncaughtException"/>

Full story: springsource forum.

like image 91
abalogh Avatar answered Sep 25 '22 04:09

abalogh