Spring 验证返回长错误消息,而不仅仅是自定义消息 [英] Spring validation returns long error messages, not just the customized message
问题描述
Spring 验证返回长错误消息,而不是自定义一次.
Spring validation returns long error message instead of the customized once.
这是dto中的代码部分.
This is the section of code in the dto.
public class RequestDto implements Serializable {
@NotNull(message="{id.required}")
private Long id;
}
在控制器中为输入添加了@Valid.
In controller added the @Valid for input.
@RequestMapping(value = ApiPath.PATH, method = RequestMethod.POST, produces = { "application/xml",
"application/json" })
public @ResponseBody ResultDecorator saveRequest(
@Valid @RequestBody RequestDto msaDisabScreenRequestDto) throws Exception {
}
API 返回以下错误.
API returns the following error.
<message>Validation failed for argument at index 0 in method: public om.gov.moh.msa.framework.resolver.ResultDecorator om.controller.MaController.saveRequest(om..dto.RequestDto) throws java.lang.Exception, with 1 error(s): [Field error in object 'requestDto' on field 'id': rejected value [null]; codes [NotNull.requestDto.id,NotNull.id,NotNull.java.lang.Long,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [requestDto.id,id]; arguments []; default message [civilId]]; **default message [ID is required.]]** </message>
自定义消息出现在最后.(默认消息 [ID 是必需的.)
Here the custom message is present at the end. (default message [ID is required.)
对全局异常使用控制器建议,我正在覆盖 handleMethodArgumentNotValid.如何在此处仅返回自定义消息?
Using Controller advice for global exception and I'm overriding handleMethodArgumentNotValid. How can I return only the custom message here?
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
/**
* Spring validation related exception
*/
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
}
推荐答案
您可以获得默认/自定义消息,例如 result.getFieldError("yourFieldName").getDefaultMessage()
You can get default/custom message like result.getFieldError("yourFieldName").getDefaultMessage()
您可以通过控制器方法捕获错误消息,应该如下所示
You can catch error messages either through controller method which should look like this
@RequestMapping(value = ApiPath.PATH, method = RequestMethod.POST, produces = { "application/xml", "application/json" })
public @ResponseBody ResultDecorator saveRequest(@Valid @RequestBody RequestDto msaDisabScreenRequestDto, BindingResult result) throws Exception {
if(result.hasErrors()){
String errorMessage = result.getFieldError("yourFieldName").getDefaultMessage();
}
}
或者通过全局异常处理程序
Or through Global Exception handler
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
/**
* Spring validation related exception
*/
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
//New Code
BindingResult bindingResult = ex.getBindingResult();
String errorMessage = result.getFieldError("yourFieldName").getDefaultMessage();
//---------------
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
apiError.setMessage(errorMessage);
return buildResponseEntity(apiError);
}
}
这篇关于Spring 验证返回长错误消息,而不仅仅是自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!