In my Spring Boot Application, I'm currently leveraging the resources/public/error/404.html custom error page to show (automagically) this 404 page errors on invalid URLS.
Is there an easy way to retain this auto functionality, and add a simple log message (with the invalid URL) for every such 404 ?
Ideally with as little code as possible I would want some like :
//Some code
LOGGER.warn("Invalid URL " + request.url);
//Some more code
You need to define a custom ErrorViewResolver:
@Component
public class MyErrorViewResolver implements ErrorViewResolver {
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
if (HttpStatus.NOT_FOUND == status) {
LoggerFactory.getLogger(this.getClass()).error("error 404 for url " + model.get("path"));
return new ModelAndView("error404", model);
}
else {
return new ModelAndView("error", model);
}
}
}
This MyErrorViewResolver will be automatically called in the BasicErrorController class.
For a 404 error, the view "error404" will be displayed.
For the other errors, the view "error" will be displayed.
Views must be in the "templates" folder (resources/templates/error404.html).
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