I'd like to return a custom 404 error using SpringBoot, but I'd like to be able to add some server-side logic to it, not just serve a static page.
1. I switched off the default whitelabel page in application.properties
error.whitelabel.enabled=false
2. I added a Thymeleaf error.html under resources/templates
This works by the way. The page is served, but no controller is called.
3. I created a class Error
to be the "Controller"
package com.noxgroup.nitro.pages;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/error")
public class Error {
@ExceptionHandler
public String index() {
System.out.println("Returning Error");
return "index";
}
}
Unfortunately, I'm not seeing Returning Error
printed anywhere in the console.
I'm using the Embedded Tomcat with Spring Boot. I've seen various options, non of which seem to work including using @ControllerAdvice, removing the RequestMapping, etc. Neither work for me.
We first need to create a custom HTML error page. If we save this file in resources/templates directory, it'll automatically be picked up by the default Spring Boot's BasicErrorController. We can be more specific by naming the file with the HTTP status code we want it used e.g. saving the file as 404.
As with any web application or website, Spring MVC returns the HTTP 404 response code when the requested resource can't be found.
The servlet container is going to pick up the 404 before it can get to Spring, so you'll need to define an error page at servlet container level, which forwards to your custom controller.
@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error"));
}
}
Easiest way I found was to implement the ErrorController.
@Controller
public class RedirectUnknownUrls implements ErrorController {
@GetMapping("/error")
public void redirectNonExistentUrlsToHome(HttpServletResponse response) throws IOException {
response.sendRedirect("/");
}
@Override
public String getErrorPath() {
return "/error";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With