Minimum Spring Boot Code to Register 404s

In my Spring boot application, I am currently using the resources / public / error / 404.html custom error page to show (automatically) this error on page 404 on invalid URLs.

Is there an easy way to preserve this automatic functionality and add a simple log message (with an invalid URL) for each such 404?

Ideally, with a minimal amount of code, I would like some to like:

//Some code
LOGGER.warn("Invalid URL " + request.url);
//Some more code
+4
source share
2 answers

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.

404 "error404".

"".

"" (resources/templates/error404.html).

+5

NotFoundException.

public class BaseController {

  // Logger declaration

  @ExceptionHandler(NotFoundException.class)
  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  @ResponseBody
  public ErrorResponse handleNotFoundError(HttpServletRequest req, NotFoundException exception) {
     List<Error> errors = Lists.newArrayList();
     errors.add(new Error(String.valueOf(exception.getCode()), exception.getMessage()));
     log.error(exception);
     return new ErrorResponse(errors);
  }
}
+2

Source: https://habr.com/ru/post/1672598/


All Articles