英文:
javax.validation.constraints with custom Code and Message
问题
我正在使用javax.validation.constraints.NotEmpty
库来验证用于REST请求的POJO类。在类中,我已经使用了以下注解。
@ApiModelProperty(value = "Name", required = true)
@NotEmpty(message = "Name is required")
private String name;
上面的代码运行良好,并在名称为空时返回以下响应:
"code": "NotEmpty",
"message": "Name is required"
有没有办法显示/提供我的自定义代码值,而不是 "code": "NotEmpty"
,类似于 "code": "INVALID NAME"
。
对此有任何方法建议将不胜感激。
英文:
I am using the javax.validation.constraints.NotEmpty
library to validate POJO class for rest request. Within class i have used below annotaion.
@ApiModelProperty(value = "Name", required = true)
@NotEmpty(message = "Name is required")
private String name;
Above code is working fine and returning the response as below when name is empty
"code": "NotEmpty",
"message": "Name is required"
Is there any way through which i can display/provide the my own Custom code value instead of "code": "NotEmpty"
. Something like "code": "INVALID NAME"
.
Any approach suggestion on this must be appreciated.
答案1
得分: 1
以下是翻译好的部分:
最佳方法是实现自己的异常处理程序并根据需要构建整个响应,可以是简单文本、JSON、XML等。
@ControllerAdvice
class ExceptionAdvisor {
@ExceptionHandler(ValidationException.class)
ResponseEntity<MyErrorType> handleTypeMismatchException(ValidationException ex) {
/*处理所有的约束违规*/
MyErrorType result = . . .;
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
}
}
还有一个Payload选项:
public static class NameInvalid implements Payload {}
.
.
.
@NotEmpty(message = "Name is required", payload = NameInvalid.class)
private String name;
这将为您提供以下结果:
"code": "NameInvalid",
"message": "Name is required"
英文:
The best way is to implement your own exception handler and build the entire response as you need to it, as simple text, JSON, XML, etc..
@ControllerAdvice
class ExceptionAdvisor {
@ExceptionHandler(ValidationException.class)
ResponseEntity<MyErrorType> handleTypeMismatchException(ValidationException ex) {
/*process all the constraint violations*/
MyErrorType result = . . .;
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
}
}
There is also the Payload option:
public static class NameInvalid implements Payload {}
.
.
.
@NotEmpty(message = "Name is required", payload = NameInvalid.class)
private String name;
Which should get you this:
"code": "NameInvalid",
"message": "Name is required"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论