我有一個簡單的代碼,當(dāng)requestBody中沒有customerId時返回錯誤json。VO課程:public class OrderVO {
private int orderId;
@NotNull(message = "CustomerId Cant be null")
private Long customerId;}控制器方法:@RequestMapping(value="/testOrderbyOrderid", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)public void testOrderJson
(@Valid @RequestBody OrderVO orderVO ) {}目前,當(dāng)requestBody中沒有customerId時,返回的JSON結(jié)構(gòu)如下所示:{
"timestamp": "2019-05-14T17:08:01.318+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [ ],
"arguments": [ ],
"defaultMessage": "CustomerId Cant be null",
"objectName": "orderVO",
"field": "customerId",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"message": "Validation failed for object='orderVO'. Error count: 1",
"path": "/testOrderbyOrderid"}如何將@Notnull返回的上述Json結(jié)構(gòu)更改為如下所示的JSON結(jié)構(gòu):{
"timestamp": "2019-05-14T17:08:01.318+0000",
"status": 400,
"error": "Bad Request",
"message": "CustomerId Cant be null"}編輯 - 我已經(jīng)知道我們可以拋出自定義異常并在ControllerAdvice中處理它,但考慮驗證所需的字段數(shù)是否為20,檢查null和throw異常所需的代碼量也會擴(kuò)大,使代碼看起來很難看。這就是我發(fā)布這個Qn的原因。
2 回答

有只小跳蛙
TA貢獻(xiàn)1824條經(jīng)驗 獲得超8個贊
將以下方法添加到控制器建議帶注釋的異常處理程序:
@Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { //return your custom error //you can access to field errors using //ex.getBindingResult().getFieldErrors() } @ExceptionHandler(value = { javax.validation.ConstraintViolationException.class }) protected ResponseEntity<Object> handleConstraintViolation( javax.validation.ConstraintViolationException ex) { //return your custom error message } @ExceptionHandler(value = { org.hibernate.exception.ConstraintViolationException.class }) protected ResponseEntity<Object> handleHibernateConstraintViolation( org.hibernate.exception.ConstraintViolationException ex) { //return your custom error message }

千萬里不及你
TA貢獻(xiàn)1784條經(jīng)驗 獲得超9個贊
我想我們也可以像這樣編寫Controller建議,而不需要擴(kuò)展ResponseEntityExceptionHandler并覆蓋它的任何方法
@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(value = { MethodArgumentNotValidException.class }) protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex){ CustomException cex = new CustomException(ex.getBindingResult().getFieldError().getDefaultMessage()); return new ResponseEntity<>(cex, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);}
添加回答
舉報
0/150
提交
取消