从自定义默认Spring验证中删除批量



我正在用从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]] "

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

是的,您可以使用全局异常处理程序来完成此操作。这是处理它的方法。

@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);
}
}

最新更新