2013-08-22 79 views
0

我想ConstraintViolationException處理ConstraintViolationException和我創建了一個簡單的約束電子郵件,並實現以用於驗證:如何休眠

EmailValidator implements ConstraintValidator<Email, String> { } 

我的問題是,當我打電話從EntityManager的堅持,它沒有趕上例外。我查看了ConstraintViolationException,發現祖先類是RuntimeException,因此它沒有被選中,但是我很困惑,因爲我看到很多文章捕捉到相同的異常。

任何人有任何意見和解決方法?

+0

爲什麼你認爲你不能捕捉運行時異常?您可以。但實體經理不會爲你抓到它。違反約束的全部要點是拋出異常。 –

+0

是的,我忘了我需要手動刷新它,這不是一個好主意。可能必須與定製驗證器解決。或者你有任何解決方法或解決這個問題? – czetsuya

+0

我不明白你在問什麼。你必須沖洗什麼,做什麼?你試圖解決什麼問題?你想實現什麼? –

回答

0

這個環節解決我的問題:Catch PersistenceException or ConstraintViolationException in JBoss AS 7

然後作爲一種解決方法我創建了一個電子郵件驗證並添加F:驗證到外地,我驗證。

@FacesValidator("emailValidator") 
public class EmailValidator implements Validator { 

public void validate(FacesContext context, UIComponent component, 
     Object value) throws ValidatorException { 

    ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", 
      Locale.ENGLISH); 

    if (StringUtils.isBlank(value)) { 
     return; 
    } else { 
     try { 
      InternetAddress emailAddr = new InternetAddress(
        value.toString()); 
      emailAddr.validate(); 
     } catch (AddressException ex) { 
      FacesMessage facesMessage = new FacesMessage(); 
      String message = resourceBundle 
        .getString("message.error.invalidEmail"); 
      message = MessageFormat.format(message, 
        getLabel(context, component)); 
      facesMessage.setDetail(message); 
      facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR); 

      throw new ValidatorException(facesMessage); 
     } 
    } 

} 

將此添加到您正在驗證的字段中。

<f:validator for="#{cc.attrs.id}_text" validatorId="emailValidator"></f:validator>