javax.validation.constraints with custom Code and Message

huangapple go评论67阅读模式
英文:

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

以下是翻译好的部分:

最佳方法是实现自己的异常处理程序并根据需要构建整个响应可以是简单文本JSONXML等

@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&lt;MyErrorType&gt; 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 = &quot;Name is required&quot;, payload = NameInvalid.class)
private String name; 

Which should get you this:

&quot;code&quot;: &quot;NameInvalid&quot;,
&quot;message&quot;: &quot;Name is required&quot; 

huangapple
  • 本文由 发表于 2023年2月16日 14:20:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定