Closed spring-projects-issues closed 12 years ago
Marcel Overdijk commented
Thinking about it..., adding a @ExceptionHandler
to a @EnableWebMvc
configuration class might be a good idea to define global exception handlers?
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
return "My error message: " + e.getMessage();
}
}
Rossen Stoyanchev commented
We can probably add this in 3.2 maybe even as early as M1. We'll need way to configure global @ExceptionHandler
methods so suggestions like yours above are welcome. One other option would be to discover a bean by name (e.g. "globalExceptionHandler") where the bean would contain one or more @ExceptionHandler
methods. A dedicated @Component
stereotype annotation might be another option but I think a name is simpler and should work.
Rossen Stoyanchev commented
This now supported through a new @ExceptionResolver
annotation. See the commit comment for details.
Rossen Stoyanchev commented
Re-opening with the intent of broadening the scope of this feature.
The creation of an @ExceptionResolver
component annotation has led to the idea of a more general component annotation for a class with globally applicable @MVC
methods such as @InitBinder
, @ModelAttribute
, and @ExceptionHandler
, which normally only apply to the controller in which they're defined. The going name for this annotation is @ControllerAdvice
.
Rossen Stoyanchev commented
Modified title (was: "Out-of-the-box support for "global" exception resolvers in combination with @ResponseBody
")
Marcel Overdijk opened SPR-9112 and commented
This Spring 3.1 example (https://github.com/rstoyanchev/spring-mvc-31-demo/tree/master/src/main/java/org/springframework/samples/mvc31/exceptionhandler) gives an example how to declare "global" exception handlers. I think the ExtendedExceptionHandlerExceptionResolver example class should in some way brought into core mvc, so it would be easier to this.
Affects: 3.1 GA
Reference URL: http://forum.springsource.org/showthread.php?120466-Handling-Exceptions-As-JSON-Spring-3-1
Issue Links:
13831 ExceptionHandlerExceptionResolver: premature null value check
Referenced from: commits https://github.com/spring-projects/spring-framework/commit/c846198e4697f2ac5d79f0f4f62d25fa7d62fa26, https://github.com/spring-projects/spring-framework/commit/e65b930e7ad63b909bd2977bff806322477f8a91, https://github.com/spring-projects/spring-framework/commit/cf147a82ef0c5592041ddfdde3d1340fd47e89aa
1 votes, 4 watchers