使用Autowired变量在spring boot中抛出自定义异常

时间:2018-03-06 17:16:32

标签: spring-mvc spring-boot exception-handling autowired

需要使用// @Component // should be a component to use autowire variable @ResponseStatus(value = HttpStatus.UNAUTHORIZED) public class MyException extends Exception { // This should be commented in // @Autowired // public RequestModel reqModel; // public MyException(ExceptionType type) { public MyException(ExceptionType type, RequestModel reqModel) { super(); switch type { // ... } } } 变量

的自定义异常
public class MyInterceptor extends HandlerInterceptorAdapter {

    // These should be commented out
    @Autowired
    public RequestModel reqModel;

    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) throws Exception {
        // This should be thrown without adding the reqModel as a param
        // Unsure how to throw this without using "new"
        throw new MyException.MyException(PARAM_MISSING, reqModel);
    }
}

然后在其余的控制器和拦截器中我们抛出错误

new

我知道使用Autowired实例化一个类会使new变量无效。当我尝试删除MyException并将@Component类转换为MyException时,我发现调用TableLayout类构造函数存在问题。

使用自动装配变量在springboot中实现自定义异常的最佳方法是什么?

0 个答案:

没有答案