我有一个Spring Boot应用程序(版本2.4.5(作为Kotlin项目。现在,当我输入无效的内容时,我会收到一条错误消息,但不会收到我在注释中设置的错误消息。
控制器
@PostMapping(value = ["/seatMap/save"])
fun addSeatPlan(@RequestPart @Valid data: DSeatMap, @RequestPart image: MultipartFile?, auth: AuthenticationToken) {
try {
if (data.uuid == null) {
seatService.addSeatMap(auth.organisation!!, data, image)
} else {
seatService.updateSeatMap(data, auth.organisation!!, image)
}
} catch (e: UnauthorizedException) {
throw e
}
}
数据类
import java.util.*
import javax.validation.constraints.NotEmpty
data class DSeatMap(
var uuid: UUID?,
@field:NotEmpty(message = "name is empty")
val name: String,
var data: String,
val quantity: Int,
var settings: DSettings?
)
我的回应,这里应该是消息=";name为空";
{
"timestamp": "2021-04-22T19:47:08.194+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='data'. Error count: 1",
}
如果我设置了属性,它会向我显示正确的属性,但我不想拥有所有的辅助信息,我只想输出消息
server.error.include-binding-errors=always
结果:
{
"timestamp": "2021-04-22T19:56:30.058+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='data'. Error count: 1",
"errors": [
{
"codes": [
"NotEmpty.data.name",
"NotEmpty.name",
"NotEmpty.java.lang.String",
"NotEmpty"
],
"arguments": [
{
"codes": [
"data.name",
"name"
],
"arguments": null,
"defaultMessage": "name",
"code": "name"
}
],
"defaultMessage": "name is empty",
"objectName": "data",
"field": "name",
"rejectedValue": "",
"bindingFailure": false,
"code": "NotEmpty"
}
],
"path": "/api/dashboard/seatMap/save"
}
@Yunz我认为"错误";属性将添加到您的响应中,因为您设置了server.error.include-binding-errors=always
可以尝试将其设置为never
,也可以不定义此属性并依赖默认值(即never
(。
您需要设置server.error.include-message=always
,因为版本2.3,Spring Boot在响应中隐藏消息字段,以避免泄露敏感信息;我们可以将此属性与"始终"值一起使用,以启用
有关详细信息,请查看spring-boot文档:
好的,我终于找到了解决方案。我创建了一个全局异常处理程序,用于侦听MethodArgumentNotValidException。之后,我操作消息并在注释中设置之前设置的验证消息
@RestControllerAdvice
class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationExceptions(ex: MethodArgumentNotValidException): Map<String, String?>? {
val errors: MutableMap<String, String?> = HashMap()
ex.bindingResult.allErrors.forEach { error: ObjectError ->
val fieldName = (error as FieldError).field
val errorMessage = error.getDefaultMessage()
errors[fieldName] = errorMessage
}
return errors
}
}
来源:https://www.baeldung.com/spring-boot-bean-validation
请使用相应的ExceptionHandler
创建以下ControllerAdvice
。应该是这样的:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
}
在最近的Spring Boot版本中,错误消息的发送被禁用,现在需要像上面所示那样手动实现。
参考:https://www.baeldung.com/spring-boot-bean-validation#the-异常处理程序注释
请在此处找到优化的解决方案:
@ControllerAdvice
public class ControllerAdvisor extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
var errors = new HashMap<>();
for (var err : ex.getBindingResult().getAllErrors())
errors.put(((FieldError) err).getField(), err.getDefaultMessage());
return this.handleExceptionInternal(ex, errors, headers, status, request);
}
}