Question: how can I handle exceptions thrown in MVC endpoints in management context?
public class MyMvcEndpoints extends EndpointMvcAdapter {
@ResponseBody
@RequestMapping(method = GET, value = "/foo", produces = APPLICATION_JSON_VALUE)
public Foo foo() {
throw new FooNotFound("Foo Not Found!");
}
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class FooNotFound extends RuntimeException {
public NotFoundException(String message){
super(message);
}
}
With the current configuration, I receive 500
instead of 404
. I tried usual approaches for exception handling like ControllerAdvice, ExceptionHandler methods, etc. No success.
I also found CompositeHandlerExceptionResolver
in EndpointWebMvcChildContextConfiguration
which is responsible for exception handling. I tried to define my own HandlerExceptionResolver
bean but it cannot find my resolver in management context.
You can use Controller Advice. Spring's @ControllerAdvice
annotation is a specialized form of @Component
that exists to handle cross cutting concerns for controllers. The most common use case is to provide exception handlers, but it can do a few other neat things as well.
@ControllerAdvice
public class ExceptionControllerAdvice {
@ExceptionHandler(Exception.class)
public ModelAndView exception(Exception e) {
ModelAndView mav = new ModelAndView("exception");
mav.addObject("name", e.getClass().getSimpleName());
mav.addObject("message", e.getMessage());
return mav;
}
}
It seems your Spring can't detect your Exception. So, one GlobalException class needs to be created with the @ControllerAdvice
and then put your exception in this. Something looks like:
public class FooNotFound extends RuntimeException {
public NotFoundException(String message){
super(message);
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(FooNotFound.class)
@ResponseStatus(value=HttpStatus. NOT_FOUND, reason="Not found")
public String handleFooNotFound(HttpServletRequest request, Exception ex){
//'SOME CODE HERE'
return "user_notfound";
}
}
Hope this help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.