2017-01-02 61 views
2

我有以下控制器逻辑。但是,如果我导航到一个不存在的页面(例如/ random-page),最终会出现TemplateInputException。我怎样才能抓住这个并转到404页面?句柄org.thymeleaf.exceptions.TemplateInputException

@RequestMapping(value = { "{path:(?!resources|error).*$}", "{path:(?!resources|error).*$}/**" }, headers = "Accept=text/html") 
public String index(final HttpServletRequest request) { 
    try { 
     String path = (String) request.getAttribute(
       HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); 
     return path.split("/")[1]; 
    } catch (Exception e) { 
     log.error("Failed to render the page. {}",e); 
     return "error/general"; 
    } 
} 

Thymeleaf似乎忽略的ExceptionHandler:

@ExceptionHandler(Exception.class) 
public ModelAndView handleAllException(Exception ex) { 

    ModelAndView model = new ModelAndView("error/generic_error"); 
    model.addObject("errMsg", "this is Exception.class"); 

    return model; 

} 
+1

有你找到了解决办法然而? – Kousalik

回答

0

我解决此问题春天启动(exception是考虑到与message PARAM):

@Controller 
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController { 
    private static final String ERROR_PATH = "/error"; 

    @Autowired 
    private ErrorAttributes errorAttributes; 

    @Override 
    public String getErrorPath() { 
     return ERROR_PATH; 
    } 

    @RequestMapping(ERROR_PATH) 
    public String error(HttpServletRequest request, Model model) { 
     Map<String, Object> errorMap = errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), false); 
     String exception = (String) errorMap.get("exception"); 
     if (exception != null && exception.contains("TemplateInputException")) { 
      errorMap.put("message", "Неверный запрос"); 
     } 
     model.addAllAttributes(errorMap); 
     return "exception"; 
    } 
}