【问题标题】:Removing bulk from custom default Spring validation从自定义默认 Spring 验证中删除批量
【发布时间】:2019-01-02 02:53:04
【问题描述】:

我正在使用从messages.properties 读取的自定义@NotNull 消息为属性编写一些基本验证。这些消息可以很好地阅读,但是大部分默认 Spring 错误消息仍然如下:

 "Validation failed for argument at index 0 in method: public java.lang.String uk.co.schedulerapi.Scheduler_Rest_Controller.bookAppointment(uk.co.apidefinitions.BookAppointment) throws java.lang.Exception, with 1 error(s): [Field error in object 'bookAppointment' on field 'windowStart': rejected value [null]; codes [NotNull.bookAppointment.windowStart,NotNull.windowStart,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookAppointment.windowStart,windowStart]; arguments []; default message [windowStart]]; default message [windowStart parameter is required]] "

是否可以删除所有错误消息并保留我的自定义消息而不进行字符串解析?

【问题讨论】:

    标签: java spring spring-boot error-handling


    【解决方案1】:

    是的,您可以使用全局异常处理程序来做到这一点。 这是处理它的方法。

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
    private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);
    
    
    @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
    public void handleException(HttpServletResponse response, Exception ex) {
        //build your custom message
        prepareErrorResponse(response,UNPROCESSABLE_ENTITY,yourCustomMessage);
    }
    
    
    
    private void prepareErrorResponse(HttpServletResponse response, HttpStatus status, String apiError) {
        response.setStatus(status.value());
        try(PrintWriter writer = response.getWriter()) {
            new ObjectMapper().writeValue(writer, apiError);
        } catch (IOException ex) {
            logger.error("Error writing string to response body", ex);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2019-01-15
      • 2016-02-13
      • 1970-01-01
      • 2015-04-25
      • 2020-12-07
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多