【发布时间】:2020-10-28 04:44:03
【问题描述】:
我向我的休息控制器发出一个发布请求,因此我想在数据不正确的情况下获取有关错误的信息。在@RestControllerAdvice中生成错误信息。
这是我的建议课:
@RestControllerAdvice
public class RestControllerErrorHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleCustomerException(MethodArgumentNotValidException exception) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("exception", "MethodArgumentNotValidException");
List<String> errors = exception
.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
body.put("errors", errors);
return body;
}
}
这是我得到的错误的结果。
{
"timestamp": "2020-07-07T20:20:44.778+00:00",
"exception": "MethodArgumentNotValidException",
"errors": [
"Login length: 6 - min and 10 - max",
"Password length: 6 - min and 10 - max"
]
}
这就是我从 ajax 调用方法 POST 的方式:
$(document).ready(function () {
$("#sendForm").click(function () {
const login = $('input[name=login]').val();
const password = $('input[name=password]').val();
$.ajax({
type: "POST",
url: "/api/users",
contentType: 'application/json',
data: JSON.stringify({"login": login, "password": password}),
dataType: "json",
success: function (data) {
alert('success: ' + data.id + " " + data.login + " " + data.password)
},
error: function (requestObject, error, errorThrown) {
alert(error);//this field return "error" string
alert(errorThrown);//for some reason this is empty when I get an error
}
});
});
});
我如何阅读它以获得准确的错误信息?我想显示这个:"Login length: 6 - min and 10 - max", "Password length: 6 - min and 10 - max" in alert()。
【问题讨论】:
标签: java jquery json ajax rest