gpt4 book ai didi

spring-mvc - 处理 org.thymeleaf.exceptions.TemplateInputException

转载 作者:行者123 更新时间:2023-12-02 01:18:41 25 4
gpt4 key购买 nike

我有以下 Controller 逻辑。但是,如果我导航到一个不存在的页面(例如/random-page),我最终会遇到 TemplateInputException。我怎样才能捕获这个并转到 404 页面?

@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;

}

最佳答案

我的 spring-boot 解决这个问题的方法(exception is view with 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";
}
}

关于spring-mvc - 处理 org.thymeleaf.exceptions.TemplateInputException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41424130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com