如何记录 SpringBoot 请求验证错误?

huangapple go评论93阅读模式
英文:

How to log SpringBoot request validation errors?

问题

  1. @GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
  2. public String sayHi(@RequestParam(name = "size") @Max(30) Integer size) {
  3. return "Hi" + size.toString();
  4. }

如果 size 的值大于 30,则该 API 会返回一个验证错误。但是,除此之外,我还想找一种记录这种无效请求的方法。

英文:

How to log request validation errors in springboot? Say, we have an API like below and I need to log if there's a validation error in one of the request params?

  1. @GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
  2. public String sayHi(@RequestParam(name = "size") @Max(30) Integer size) {
  3. return "Hi" + size.toString();
  4. }

If the size value is more than 30 then the API returns a validation error. But, along with that, I'm also looking for a way to log such invalid requests

答案1

得分: 0

  1. 由于您正在使用 Spring Boot您可以使用 `@ControllerAdvice` 来实现 Spring Boot 的异常处理集中化以便记录这些错误或返回自定义的通用响应类`@ControllerAdvice` 注解将使其在全局范围内适用于所有控制器
  2. 为了捕获请求体的验证错误我们将处理 `MethodArgumentNotValidExceptions`如下所示
  3. @ControllerAdvice
  4. class ErrorHandlingControllerAdvice {
  5. private static final Logger LOGGER = LoggerFactory.getLogger(ErrorHandlingControllerAdvice.class);
  6. @ExceptionHandler(ConstraintViolationException.class)
  7. @ResponseStatus(HttpStatus.BAD_REQUEST)
  8. @ResponseBody
  9. ApiErrorResponse onConstraintValidationException(
  10. ConstraintViolationException e) {
  11. ApiErrorResponse apiErrorResponse = new ApiErrorResponse();
  12. for (ConstraintViolation violation : e.getConstraintViolations()) {
  13. apiErrorResponse.getViolations().add(
  14. new Violation(violation.getPropertyPath().toString(), violation.getMessage()));
  15. }
  16. return apiErrorResponse;
  17. }
  18. @ExceptionHandler(MethodArgumentNotValidException.class)
  19. @ResponseStatus(HttpStatus.BAD_REQUEST)
  20. @ResponseBody
  21. ApiErrorResponse onMethodArgumentNotValidException(
  22. MethodArgumentNotValidException e) {
  23. ApiErrorResponse error = new ApiErrorResponse();
  24. for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
  25. error.getViolations().add(
  26. new Violation(fieldError.getField(), fieldError.getDefaultMessage()));
  27. }
  28. LOGGER.error("在这里记录您想要的日志信息");
  29. return error;
  30. }
  31. }
英文:

Since you are using springboot , you could use spring boot centralized exception handling using @ControllerAdvice to log these errors or return a custom common response class . The @ControllerAdvice annotation will make it apply globally to all controllers.
In order to catch validation errors for request bodies , we will handle MethodArgumentNotValidExceptions like:

  1. @ControllerAdvice
  2. class ErrorHandlingControllerAdvice {
  3. private static final Logger LOGGER = LoggerFactory.getLogger(ErrorHandlingControllerAdvice.class);
  4. @ExceptionHandler(ConstraintViolationException.class)
  5. @ResponseStatus(HttpStatus.BAD_REQUEST)
  6. @ResponseBody
  7. ApiErrorResponse onConstraintValidationException(
  8. ConstraintViolationException e) {
  9. ApiErrorResponse apiErrorResponse = new ApiErrorResponse();
  10. for (ConstraintViolation violation : e.getConstraintViolations()) {
  11. apiErrorResponse.getViolations().add(
  12. new Violation(violation.getPropertyPath().toString(), violation.getMessage()));
  13. }
  14. return apiErrorResponse;
  15. }
  16. @ExceptionHandler(MethodArgumentNotValidException.class)
  17. @ResponseStatus(HttpStatus.BAD_REQUEST)
  18. @ResponseBody
  19. ApiErrorResponse onMethodArgumentNotValidException(
  20. MethodArgumentNotValidException e) {
  21. ApiErrorResponse error = new ApiErrorResponse();
  22. for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
  23. error.getViolations().add(
  24. new Violation(fieldError.getField(), fieldError.getDefaultMessage()));
  25. }
  26. LOGGER.error("Log whatever you want to here");
  27. return error;
  28. }
  29. }

huangapple
  • 本文由 发表于 2020年10月20日 14:55:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64439943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定