Input Validation Spring Boot using BindingResult - achille005/DevMaterials GitHub Wiki

@PostMapping(path="internalTransfer")
public  ResponseEntity<Object> internalFundTransfer(@Parameter(description = "", required = true) @Valid @RequestBody Request request,final BindingResult bindingResult)throws InvalidInputException{
	processResultBinding(bindingResult);
	Response response = new Response;
	return new ResponseEntity<>(response, HttpStatus.OK);
}


private void processResultBinding(BindingResult bindingResult) {
	
			if ((bindingResult != null && bindingResult.hasErrors())) {
				String completeErrorList = "";
				completeErrorList = bindingResult.getAllErrors().stream().map(br -> br.getDefaultMessage()).reduce(" ",
						(prev, newElem) -> prev + newElem + " ");
				ErrorResponse ewd = new ErrorResponse().errorCode("INTERNAL_FUND_TRANSFER")
						.errorDescription("IO Validation Failed Intrernal Fund Transfer ")
						.className(this.getClass().getName())
						.developerMessage("bindingResult has errors " + bindingResult.getErrorCount() + " " + completeErrorList)
						.messageToCustomer("Please correct the errors in input" + completeErrorList)
						.path(this.getClass().getAnnotation(RestController.class).value()).method(HttpMethod.POST.name())
						.category(ErrorCategory.INPUT_OUTPUT).type(ErrorType.VALIDATION);
				log.error(ewd.getLogMessage());
				Map<String, String> valErrorMap = new HashMap<String, String>();
				int countOfAllErrors = bindingResult.getErrorCount();
				if (bindingResult.hasFieldErrors() && countOfAllErrors > 0) {
					int i = 0;
					for (FieldError fe : bindingResult.getFieldErrors()) {
						valErrorMap.put("FieldName"+i, fe.getField());
						valErrorMap.put("FieldErrorMessage"+i, fe.getDefaultMessage());
						i++;
						countOfAllErrors--;
					}
				}
				if (bindingResult.hasGlobalErrors() && countOfAllErrors > 0) {
					int i = 0;
					for (ObjectError er : bindingResult.getGlobalErrors()) {
						valErrorMap.put("GlobalErrorField_"+i,er.getObjectName());
						valErrorMap.put("GlobalErrorFieldMessage_"+i,er.getDefaultMessage());
						i++;
						countOfAllErrors--;
					}
				}
				if (bindingResult.hasErrors() && countOfAllErrors > 0) {
					int i = 0;
					for (ObjectError er : bindingResult.getAllErrors()) {
						valErrorMap.put("OtherErrorField_"+i,er.getObjectName());
						valErrorMap.put("OtherErrorFieldMessage_"+i, er.getDefaultMessage());
						i++;
						countOfAllErrors--;
					}
				}
				ewd.validationErrors(valErrorMap);
				throw new InvalidInputException(this.getClass().getName(), ewd);

			}
			
			
			
			public class InvalidInputException extends CommonException {

private static final long serialVersionUID = 1490271211048414655L;

public InvalidInputException(String exceptionClassName, Error error) {
	super(exceptionClassName, error);
}

public void printStackTrace() {
	this.printStackTrace(System.err);
}

@Override
public String getExceptionAsJsonString() {
	return getErrorResponse().getJsonAsString(getErrorResponse());
}

public InvalidInputException(String exceptionClassName, ErrorResponse errorResponse) {
	super(exceptionClassName, errorResponse);
	// TODO Auto-generated constructor stub
}

}

public abstract class CommonException extends RuntimeException { /** * */ private static final long serialVersionUID = -186187720830084340L;

private String exceptionClassName;

private ErrorResponse errorResponse;

public CommonException() {
	super();
}

public CommonException(String message) {
	super(message);
}

public CommonException(Throwable t) {
	super(t.toString());
}

public CommonException(String message, Throwable t) {
	super(message);
}

public CommonException(Throwable msg, Throwable t) {
	super(t.getMessage());
}

public CommonException(String exceptionClassName, ErrorResponse errorResponse) {
	super();
	this.exceptionClassName = exceptionClassName;
	this.errorResponse = errorResponse;
}

public String getExceptionClassName() {
	return exceptionClassName;
}

public void setExceptionClassName(String exceptionClassName) {
	this.exceptionClassName = exceptionClassName;
}

public String exceptionName() {
	return this.getClass().getName();
}

public String getExceptionLogMessage() {
	return "exceptionClassName=" + this.exceptionClassName + "|" + errorResponse.getLogMessage();
}


public ErrorResponse getErrorResponse() {
	return errorResponse;
}

public void setErrorResponse(ErrorResponse errorResponse) {
	this.errorResponse = errorResponse;
}

public abstract String getExceptionAsJsonString();

}

@JsonProperty("aFieldName")
@NotNull
    private String aFieldName;
⚠️ **GitHub.com Fallback** ⚠️