我正在使用从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]] "
是否可以删除所有错误消息并保留我的自定义消息而不进行字符串解析?
答案 0 :(得分:0)
是的,您可以使用全局异常处理程序来实现。 这是处理它的方法。
@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);
}
}