I've been trying to handle globally a situation when my dispatcher servlet doesn't have defined mapping for requested url but haven't found the solution yet.
Here's my class for handling global exceptions:
@ControllerAdvice
public class GlobalExceptionHandlerController {
@Value("${exception.view.default}")
private String defaultExceptionView;
private static final Logger LOGGER = Logger.getLogger(GlobalExceptionHandlerController.class);
@ExceptionHandler(Exception.class)
public ModelAndView notFoundException(Exception e) {
LOGGER.error("Error ocurred: " + e.getMessage());
return new ModelAndView(defaultExceptionView)
.addObject("code", "404")
.addObject("name", "Page Not Found")
.addObject("message", "We couldn't find requested resource");
}
}
I tried many different classes within @ExceptionHandler but nothing worked for me. The handler works fine - when I throw exception from one of the controllers and it isn't handled locally it goes straight to this global handler.
Is there a way to perform that kind of exception handling by @ControllerAdvice?
Yes, configure your DispatcherServlet
with setThrowExceptionIfNoHandlerFound
which sets
[...] whether to throw a
NoHandlerFoundException
when noHandler
was found for this request. This exception can then be caught with aHandlerExceptionResolver
or an@ExceptionHandler
controller method.
and do what it says, ie. define an @ExceptionHandler
for a NoHandlerFoundException
exception.
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.