2 回答

TA貢獻1866條經驗 獲得超5個贊
我認為您應該使用@RestControllerAdvice注釋,因為違反約束是一個例外。我認為通過異常處理這個比使用自定義驗證器更有效。您可以為您的特定業務邏輯使用驗證器。
例如:
public class ConstraintViolationException extends BaseApiRuntimeException {
private static final long serialVersionUID = 1L;
public ConstraintViolationException([module eg. enum of project modules] module, String resource) {
super(module, resource);
}
}
BaseApiRuntimeException 僅擴展 RuntimeException。包裝它將使您更靈活地自定義異常消息。
使用控制器建議構建異常處理程序:
@RestControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorDetail> handleConstraintViolationException(
HttpServletRequest request, ConstraintViolationException base) {
LOG.info("CONSTRAINT VIOLATION EXCEPTION: ", base);
ErrorDetail error = new ErrorDetail<ConstraintViolationException>().setErrorDetails(
CONSTRAINT_VIOLATION, base, "CONSTRAINT VIOLATION USERNAME ALREADY EXIST.");
return new ResponseEntity<ErrorDetail>(error, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
您可以在此處創建自己的包裝器以生成自定義響應。在這個例子中是 ErrorDetail 類。搜索RestControllerAdvice以獲取更多詳細信息。您還可以針對您的特定用例將 basePackages 添加到此注釋中。
編輯:服務層
你可以這樣使用:
throw new ConstraintViolationException([module package e.g enum or string],
"any custom message here: " + anything);

TA貢獻1906條經驗 獲得超10個贊
我更改了 UniqueUserNameValidator 類:
public class UniqueUserNameValidator implements ConstraintValidator<UniqueUserName, String> {
@Autowired
private UserService userServicel;
private String message;
@Override
public void initialize(UniqueUserName constraintAnnotation) {
message = constraintAnnotation.message();
}
@Override
public boolean isValid(String userName, ConstraintValidatorContext constraintValidatorContext) {
boolean valid = true;
try {
valid = userName != null && !userServicel.checkUserNameExits(userName);
} catch (Exception e) {
}
if (!valid) {
constraintValidatorContext.buildConstraintViolationWithTemplate(message)
.addConstraintViolation()
.disableDefaultConstraintViolation();
}
return valid;
}
}
這沒有錯誤。謝謝大家幫助我?。?!
添加回答
舉報