Handle error 404 in web application - not REST application

后端 未结 3 598
不知归路
不知归路 2021-01-05 23:10

I\'m trying to handle 404 error using an @ControllerAdvice in a Spring MVC application totally configured using Javaconfig.

Spring MVC version is 4.1.5<

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 23:56

    Workaround: Add @RequestMapping("/**")

    @Controller
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
        @RequestMapping("/**")
        public String handlerNotMappingRequest(HttpServletRequest request, HttpServletResponse response, HttpHeaders httpHeaders)
                throws NoHandlerFoundException {
            throw new NoHandlerFoundException("No handler mapping found.", request.getRequestURL().toString(), httpHeaders);
        }
    
        @ExceptionHandler(Throwable.class)
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public ModelAndView handleControllerException(Throwable ex) {
            logger.error("ErrorLog: ", ex);
            return new ModelAndView("error/exception", "exceptionMsg", "ExceptionHandler msg: " + ex.toString());
        }
    
        @ExceptionHandler(NoHandlerFoundException.class)
        @ResponseStatus(HttpStatus.NOT_FOUND)
        public ModelAndView handleNoHandlerFoundException(NoHandlerFoundException ex) {
            logger.error("ErrorLog: ", ex);
            return new ModelAndView("error/exception", "exceptionMsg", "NoHandlerFoundException msg: " + ex.toString());
        }
    }
    

提交回复
热议问题