2011-11-17 60 views
1

運行ex.getMessage()插值消息給我:如何獲得對Hibernate的ValidationException驗證

Property 'firstname' threw exception; nested exception is javax.validation.ValidationException: 
Error validating field firstname of class com.inferoquest.entity.Employee: 
[ConstraintViolationImpl{interpolatedMessage='Name cannot be shorter than 2 characters', 
propertyPath=firstname, rootBeanClass=class com.inferoquest.entity.Employee, 
messageTemplate='Name cannot be shorter than 2 characters'}] 

從中我想提取Name cannot be shorter than 2 characters。 更新:也許我還應該補充說,我想以乾淨的方式做到這一點,而不是通過正則表達式:-)

我已經看到this關於這個問題的線程。它的答案可能包含我的解決方案,但說實話,我認爲這樣一個簡單的任務看起來過於複雜,並且實際上不能很好地理解它。

任何想法?

回答

3

A ConstraintViolationException包裝了一套ConstraintViolations(有關更多詳細信息,請參閱JavaDoc)。您可以通過調用getConstraintViolations()上捕獲的異常來獲取這些違規,遍歷該集合並生成包含所有違規消息的消息。

+0

這就是問題所在,它是拋出的ValidationException而不是ConstraintViolationException,並且拋出異常似乎並沒有讓我有任何好處。有任何想法嗎? –

+0

哪一層/框架拋出異常? 'ValidationException'源自哪裏?也許它有一個'ConstraintViolationException'作爲原因? – Gunnar

0

執行到上述解決方案。

@RestControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class) 
public class GlobalExceptionHandler { 

    @ExceptionHandler(ConstraintViolationException.class) 
    public ResponseObject handleConstaintViolatoinException(final ConstraintViolationException ex) { 

    StringBuilder message = new StringBuilder(); 
    Set<ConstraintViolation<?>> violations = ex.getConstraintViolations(); 
    for (ConstraintViolation<?> violation : violations) { 
     message.append(violation.getMessage().concat(";")); 
    } 
    return new ResponseObject(HttpStatus.PRECONDITION_FAILED.value(), message.toString()); 
    } 
}