使用绑定变量自定义Spring异常

时间:2013-10-04 12:10:24

标签: java spring spring-mvc

我想创建一个自定义业务例外:

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 rest controller中使用它:

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

    }

}

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

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

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

我建议封装在BusinessException中创建错误消息所需的所有内容。你已经传递了code作为一系列参数的一部分。使用getParams()方法公开整个数组,或者(这是我将采用的方法)将代码字段和getCode()方法添加到BusinessException并添加code BusinessException的构造函数的参数。然后,您可以更新handleException以获取BusinessException而不是Exception,并在创建用于创建消息的参数时使用getCode()