2013-10-04 30 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()