@NotNull : validation custom message not displaying

时光毁灭记忆、已成空白 提交于 2020-08-24 03:31:48

问题


I am using spring data JPA for creating application. In that I am trying to implement server side validation using annotation. I added @NotNull annotation on filed with custom message. I also added @valid with @RequestBody

But problem is that when I am passing nAccountId as null I am not getting custom message i.e. Account id can not be null I am getting "message": "Validation failed for object='accountMaintenanceSave'. Error count: 1",.

Can any one please tell me why I am not getting custom message?

Controller code

@PutMapping("/updateAccountData")
public ResponseEntity<Object> saveData(@Valid @RequestBody AccountMaintenanceSave saveObj){
    return accService.saveData(saveObj);
} 

AccountMaintenanceSave class

import javax.validation.constraints.NotNull;

public class AccountMaintenanceSave {   

    @NotNull(message="Account id can not be null")
    public Integer nAccountId;
    @NotNull
    public String sClientAcctId;
    @NotNull
    public String sAcctDesc;
    @NotNull
    public String sLocation;
    @NotNull
    public Integer nDeptId; 
    @NotNull
    public Integer nAccountCPCMappingid;
    @NotNull
    public Integer nInvestigatorId;

    //Getter and Setter
}

RestExceptionHandler class

@ControllerAdvice
public class RestExceptionHandler { 

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleAllExceptionMethod(Exception ex, WebRequest requset) {

        ExceptionMessage exceptionMessageObj = new ExceptionMessage();

        exceptionMessageObj.setMessage(ex.getLocalizedMessage());
        exceptionMessageObj.setError(ex.getClass().getCanonicalName());
        exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());

        // return exceptionMessageObj;
        return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

I don't know what exactly happen previously and not getting proper message. Now using same code getting result like this with proper message

{
  "message": "Validation failed for argument at index 0 in method: public org.springframework.http.ResponseEntity<java.lang.Object> com.spacestudy.controller.AccountController.saveData(com.spacestudy.model.AccountMaintenanceSave), with 1 error(s): [Field error in object 'accountMaintenanceSave' on field 'nAccountId': rejected value [null]; codes [NotNull.accountMaintenanceSave.nAccountId,NotNull.nAccountId,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [accountMaintenanceSave.nAccountId,nAccountId]; arguments []; default message [nAccountId]]; default message [Account id can not be null]] ",
  "error": "org.springframework.web.bind.MethodArgumentNotValidException",
  "path": "/spacestudy/rockefeller/admin/account/updateAccountData"
}

In message filed can I print only [Account id can not be null]?


回答1:


Try this.

@ControllerAdvice
public class RestExceptionHandler { 

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleAllExceptionMethod(Exception ex, WebRequest requset) {

    ExceptionMessage exceptionMessageObj = new ExceptionMessage();

    // Handle All Field Validation Errors
    if(ex instanceof MethodArgumentNotValidException) {
        StringBuilder sb = new StringBuilder(); 
        List<FieldError> fieldErrors = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors();
        for(FieldError fieldError: fieldErrors){
            sb.append(fieldError.getDefaultMessage());
            sb.append(";");
        }
        exceptionMessageObj.setMessage(sb.toString());
    }else{
        exceptionMessageObj.setMessage(ex.getLocalizedMessage());
    }

    exceptionMessageObj.setError(ex.getClass().getCanonicalName());
    exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());

    // return exceptionMessageObj;
    return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
  }
}



回答2:


It's not so good to make your only ExceptionHandler to catch Exception.class make it ConstraintViolationException.class




回答3:


Can you try the below code?

import javax.validation.constraints.NotNull;

public class AccountMaintenanceSave { 

@NotNull(nullable=false,message="Account id can not be null")
public Integer nAccountId;
@NotNull
public String sClientAcctId;
@NotNull
public String sAcctDesc;
@NotNull
public String sLocation;
@NotNull
public Integer nDeptId; 
@NotNull
public Integer nAccountCPCMappingid;
@NotNull
public Integer nInvestigatorId;

//Getter and Setter
}


来源:https://stackoverflow.com/questions/52386294/notnull-validation-custom-message-not-displaying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!