I would like to redirect to my custom error page (/error/page) when a Thymeleaf error happens (ie fragment doesn't exist).
My problem is that the whole error page gets rendered into the Thymeleaf fragment if it has any errors.
I have tried writing a custom error handler, and a custom error controller, and it works fine for any other exceptions (redirects to my custom error page), but not when a Thymeleaf error happens.
@Controller
public class CustomErrorController implements ErrorController {
private final String ERROR_PATH = "/error";
@RequestMapping(ERROR_PATH)
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
if (statusCode == HttpStatus.NOT_FOUND.value()) {
return "redirect:/error/page";
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "redirect:/error/page";
}
}
// Thymeleaf error -> status code 200 and doesn't work redirect
return "redirect:/error/page";
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@ModelAttribute(name = "url")
public String getUrl(@AuthenticationPrincipal User user) {
return user != null
? "rooms"
: "";
}
}
@Controller
public class DefaultErrorController {
@RequestMapping("/error/page")
public String handleError() {
return "errors/error";
}
@ModelAttribute(name = "url")
public String getUrl(@AuthenticationPrincipal User user) {
return user != null
? "rooms"
: "";
}
}
public class ThymeleafErrorFilter implements Filter {
@Override
public void init(final FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
filterChain.doFilter(servletRequest, servletResponse);
} catch (final NestedServletException nse) {
if(nse.getCause() instanceof TemplateEngineException) {
// redirec to error page
}
throw nse;
}
}
@Override
public void destroy() {
}
}
Application.properties:
############## ERROR PAGE ################
server.error.whitelabel.enabled=false
server.error.path=/error
@EnableAutoConfiguration AppConfig.java
@Bean
public FilterRegistrationBean<ThymeleafErrorFilter> thymeleafErrorFilter() {
var thymeleafErrorFilter = new FilterRegistrationBean<ThymeleafErrorFilter>();
thymeleafErrorFilter.setName("thymeleafErrorFilter");
thymeleafErrorFilter.setFilter(new ThymeleafErrorFilter());
thymeleafErrorFilter.addUrlPatterns("/*");
return thymeleafErrorFilter;
}
If thymeleaf fragments don't exist. We detected it in ThymeleafErrorFilter. After the spring call /error (we catch it in CustomErrorController) and in CustomErrorController, the status code is 200, and redirect doesn't work.
You should use @ControllerAdvise to handle your Exceptions and provide a view to render the error.
See this:
@ControllerAdvice
@Slf4j
public class ErrorControllerAdvice {
@ExceptionHandler(StorageException.class) //handle this exception
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String storageException(final StorageException throwable, final Model model) {
log.error("Exception during execution of application", throwable);
model.addAttribute("errorMessage", "Failed to store file"); //custom message to render in HTML
return "error"; //the html page in resources/templates folder
}
/// handle other exeptions
The view:
error.html
<h1> Opps.. Sorry about this. </h1>
<p th:utext="${errorMessage}"></p>
See https://github.com/gtiwari333/spring-boot-blog-app/blob/master/src/main/java/gt/app/web/mvc/ErrorControllerAdvice.java for more details.
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.