2013-10-04 36 views
1

我想創建一個自定義的業務異常:定製春天例外綁定變量

public class BusinessException extends RuntimeException { 

    private static final long serialVersionUID = 1L; 

    public BusinessException(String msg) { 

     super(msg); 
    } 

    public BusinessException(String msg, Object[] params) { 

     //Not sure how to pass params to @ExceptionHandler 

     super(msg); 
    } 

} 

,並在我的Spring MVC的休息控制器使用它:

@RequestMapping(value = "/{code}", method = RequestMethod.GET) 
    public @ResponseBody 
    String getState(@PathVariable String code) throws Exception { 
     String result; 
     if (code.equals("KL")) { 
      result = "Kerala"; 
     } else { 

      throw new BusinessException("NotAValidStateCode",new Object[]{code}); 
     } 
     return result; 
    } 

我處理所有使用普通的businessException異常處理程序:

@ControllerAdvice 
public class RestErrorHandler { 

    private static final Logger LOGGER = LoggerFactory 
      .getLogger(RestErrorHandler.class); 

    @Autowired 
    private MessageSource messageSource; 

    @ExceptionHandler(BusinessException.class) 
    @ResponseStatus(HttpStatus.BAD_REQUEST) 
    @ResponseBody 
    public String handleException(

    Exception ex) { 

     Object[] args=null; // Not sure how do I get the args from custom BusinessException 

     String message = messageSource.getMessage(ex.getLocalizedMessage(), 
       args, LocaleContextHolder.getLocale()); 

     LOGGER.debug("Inside Handle Exception:" + message); 

     return message; 

    } 

} 

現在我的問題是,我想從消息中讀取消息文本s屬性文件,其中一些鍵需要運行時綁定變量,例如

NotAValidStateCode= Not a valid state code ({0}) 

我不知道如何將這些參數傳遞給handleException方法的RestErrorHandler。

回答

1

這是簡單,因爲你已經做了所有的 「繁重」:

public class BusinessException extends RuntimeException { 

    private static final long serialVersionUID = 1L; 

    private final Object[] params; 

    public BusinessException(String msg, Object[] params) { 
     super(msg); 
     this.params = params; 
    } 

    public Object[] getParams() { 
     return params; 
    } 

} 

@ExceptionHandler 
@ResponseStatus(HttpStatus.BAD_REQUEST) 
@ResponseBody 
public String handleException(BusinessException ex) { 
    String message = messageSource.getMessage(ex.getMessage(), 
      ex.getParams(), LocaleContextHolder.getLocale()); 
    LOGGER.debug("Inside Handle Exception:" + message); 
    return message; 
} 
0

我建議封裝一切你需要在BusinessException中創建錯誤消息。作爲params數組的一部分,您已經傳入code。或者用getParams()方法公開整個數組,或者(並且這是我將採用的方法)將代碼字段和getCode()方法添加到BusinessException,並將code參數添加到BusinessException的構造函數。然後,您可以更新handleException以獲取BusinessException而不是Exception,並在創建用於創建消息的參數時使用getCode()