Member-only story
How to customize error page selection logic in Spring Boot
Spring Boot provides a comprehensive error handling for web applications and REST services using its BasicErrorController
. This class has an important extension point — ErrorViewResolver
that allows us to customize the logic of selecting pages for different errors.
In a simple case, if you want to change how the “Whitelabel Error Page” looks like, you can simply create a custom page and put it into a conventional location. E.g. to handle error 404, just put a page named 404.html
into resources/public/error
folder of your project.
But this may not be enough if your pages are located in a different place or if you want to customize the logic used to select them for a particular error.
Suppose we have the following controller with a /goodpage
and a /badpage
that for some reason produces an error. We can use the bad page to simulate the server-side error:
@Controller
public class MyController {
@GetMapping("/goodpage")
public String goodpage() {
return "good";
}
@GetMapping("/badpage")
public String badpage() {
throw new RuntimeException("Bad!");
}
}
Now we want to show a special view located at resources/public/mycustomfolder/oops.html
every time a nasty server-side 5xx error happens and keep the default…