2017-02-01 5 views
0

엔티티 설정자에서 기본 유효성 검사를 수행하고 모델이 유효하지 않은 경우 도메인 예외를 발생시키는 sdr 프로젝트가 있습니다. 예외 내에서 메시지 소스를 가져올 수 없기 때문에 비즈니스 예외 메시지를 현지화 할 수 있습니다. 내가 시도 사용자 정의 예외 클래스는 다음과 같습니다스프링 데이터 나머지 i18n 도메인 예외

@ResponseStatus(org.springframework.http.HttpStatus.CONFLICT) 
public class DoublePriceException extends Exception { 

    @Autowired 
    static ReloadableResourceBundleMessageSource messageSource; 

    private static final long serialVersionUID = 1L; 

    public DoublePriceException(OrderItem orderItem) { 

     super(String.format(
       messageSource.getMessage("exception.doublePricedItem", null, LocaleContextHolder.getLocale()), 
       orderItem.name)); 

    } 

} 

을 내가 던질하려고 어떻게 mofo은 다음과 같습니다

public void setPrices(List<Price> prices) throws DoublePriceException { 

     for (Price price : prices) { 

      List<Price> itemsPrices = prices.stream().filter(it -> price.item.equals(it.item)).collect(Collectors.toList()); 

      if(itemsPrices.size() > 1) 
       throw new DoublePriceException(itemsPrices.get(0).item); 

     } 

     this.prices = prices; 

    } 

MessageSource를 항상 null입니다. 나는 성취 할 수없는 것을 시도하고 있는가?

답변

1

DoublePriceException은 Spring 관리 Bean이 아니기 때문에 분명히 작동하지 않습니다.

응용 프로그램에서 예외를 처리하고 적절한 응답을 생성하는 ControllerAdvice을 등록 할 수 있습니다. 스프링 프레임 워크에 의해 주사 패키지에 상기 배치는

/** 
* Spring MVC @link {@link ControllerAdvice} which 
* is applied to all Controllers and which will handle 
* conversion of exceptions to an appropriate JSON response. 
*/ 
@ControllerAdvice 
public class ErrorHandlingAdvice 
{ 
    /** 
    * Handles a @DoublePriceException 
    * 
    * @param ex the DoublePriceException 
    * 
    * @return JSON String with the error details. 
    */ 
    @ExceptionHandler(DoublePriceException.class) 
    @ResponseStatus(HttpStatus.BAD_REQUEST) 
    @ResponseBody 
    public Object processValidationError(DoublePriceException ex) 
    { 
    //return suitable representation of the error message 
    //e.g. return Collections.singletonMap("error", "my error message"); 
    } 
} 

이 적용된 감지하기에 충분해야한다.

+0

나는이 작업을 가져올 수 없습니다. "org.springframework.http.converter.HttpMessageNotReadableException : 문서를 읽을 수 없습니다 : DoublePriceException"이 계속 나타납니다. 나는 스프링 부트 1.4.0을 사용하고 있으며 행운이없는 @RestControllerAdvice도 시도했다. – aycanadal

0

나는 HttpMessageNotReadableException을 잡기와 다음과 같은 getMostSpecificCause()를 호출을 마련 할 수 최저 :

@RestControllerAdvice 
public class ExceptionHandlingAdvice { 

    @Autowired 
    private MessageSource messageSource; 

    @ExceptionHandler(HttpMessageNotReadableException.class) 
    public ResponseEntity<Object> onException(HttpMessageNotReadableException ex, WebRequest request) { 

     Locale locale = request.getLocale(); 
     Throwable cause = ex.getMostSpecificCause(); 
     String message = cause.getMessage(); 

     if (cause instanceof MultiplePriceException) { 

      message = messageSource.getMessage("exception.multiple.price", 
        new Object[] { ((MultiplePriceException) cause).orderItem.name }, locale); 

     } 

     return new ResponseEntity(Collections.singletonMap("error", message), new HttpHeaders(), 
       HttpStatus.BAD_REQUEST); 

    } 
} 
관련 문제