'spring boot doesn't shows custom error pages
I added spring-boot-starter-thymeleaf
dependency to my project that using spring boot 2.3.1.RELEASE and placed error.html
file inside src/main/resources/templates
with name error.html and other custom error pages inside
src/main/resources/templates/error` as you can see in below image:
and add this configuration in application.yml:
server:
error:
whitelabel:
enabled: false
and exclude ErrorMvcAutoConfiguration
by add @SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
into Application
class.
But, unfortunately i see this below page when error occurs, for example for 404 error!
How can i solve this problem? i also googled for this but didn't find anything to help.
Solution 1:[1]
Try to use WebServerFactoryCustomizer
:
@Configuration
public class WebConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.addErrorPages(
new ErrorPage(HttpStatus.FORBIDDEN, "/403"),
new ErrorPage(HttpStatus.NOT_FOUND, "/404"),
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
}
}
And ErrorController:
@Controller
public class ErrorController {
@GetMapping("/403")
public String forbidden(Model model) {
return "error/403";
}
@GetMapping("/404")
public String notFound(Model model) {
return "error/404";
}
@GetMapping("/500")
public String internal(Model model) {
return "error/500";
}
@GetMapping("/access-denied")
public String accessDenied() {
return "error/access-denied";
}
}
I have the same structure and it works for me:
Example: Customize the Error Messages
PS: in mine application.yml
i don't have any properties for error handling
Solution 2:[2]
You don't need to exclude ErrorMvcAutoConfiguration
.
Simply put error pages to these places.
see also:
Solution 3:[3]
add this configuration in application.yml/application.properties:
- server.error.path=/error
creat your error pages inder error path
- error/400.html
- error/500.html
- error/error.html
create class implements ErrorController:
@Controller
public class MyErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if (status != null) { Integer statusCode = Integer.valueOf(status.toString()); if(statusCode == HttpStatus.NOT_FOUND.value()) { return "/error/404"; } else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) { return "/error/500"; } } return "/error/error";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | DEWA Kazuyuki - ???? |
Solution 3 | Sekrafi Abdallah |