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;
    }

我正在使用通用异常处理程序处理所有业务异常:

@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;

    }

}

现在我的问题是,我想从消息属性文件中读取消息文本,其中一些键需要运行时绑定变量,例如

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

我不确定如何将这些参数传递给 RestErrorHandler 的 handleException 方法。

4

2 回答 2

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;
}
于 2013-10-06T10:20:20.973 回答
0

我建议将创建错误消息所需的所有内容封装在BusinessException. 您已经code作为参数数组的一部分传入。要么用一个方法公开整个数组getParams(),要么(这是我将采用的方法)添加一个代码字段和getCode()方法,并向的构造函数BusinessException添加一个code参数。然后,您可以在创建用于创建消息的参数时BusinessException更新handleException以采用 aBusinessException而不是 anException和使用。getCode()

于 2013-10-06T09:50:22.200 回答