2017-05-16 77 views
0

我有一个弹簧引导应用程序。我有一个类是ControllerAdvice来处理应用程序抛出的异常。SpringBoot - 过滤器异常处理程序

我创建了一个filter,我想用它来验证所有请求的标头。当我从该过滤器抛出自定义异常时,它不通过我的异常处理程序,它使用默认的Spring错误控制。

有没有办法以我自己的方式处理过滤器中的错误?

+0

请发布代码,您在哪里抛出该错误以及您试图捕获它的位置。 –

+1

你有没有尝试在你的过滤器而不是'ControllerAdvice'中写入'ExceptionHandler'?因为请求可能无法到达您的DipatcherServlet。 – ansh

回答

1

粘贴到这个你application.properties

spring.mvc.throw-exception-if-no-handler-found=true 
+0

在spring.boot.version 1.3.3.RELEASE – JRichardsz

0

你可以写一个扩展BasicErrorController控制器和写有@GetMapping注解这样的方法:

@RestController 
public class FilterExceptionController extends BasicErrorController { 

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

    public FilterExceptionController(){ 
     super(new DefaultErrorAttributes(),new ErrorProperties()); 
    } 

    @GetMapping 
    private <T> ResponseResult<T> serviceExceptionHandler(HttpServletRequest request) { 
     Map<String,Object> body= getErrorAttributes(request,isIncludeStackTrace(request,MediaType.ALL)); 
     String message = String.valueOf(body.get("message")); 
     body.forEach((k,v)->LOGGER.info("{} ==> {}",k,v)); 
     return RestResultGenerator.genError(500,"Filter Error Occurred, Message: [ "+message+" ]"); 
    } 

    @Override 
    public String getErrorPath() { 
     return "/error"; 
    } 
} 

有我的测试过滤器:

@WebFilter(filterName = "ipFilter",urlPatterns = "/*") 
public class IpFilter implements Filter{ 
    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 

    } 

    @Override 
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 
     if(!Arrays.asList(new String[]{"127.0.0.1"}).contains(servletRequest.getRemoteAddr())){ 
      throw new ServiceException(403,"ip forbid"); 
     } 
    } 

    @Override 
    public void destroy() { 

    } 
} 

Thi s是结果(但只能得到异常消息不是代码): enter image description here

+0

中不起作用,并且还可以进入具有'@ ControllerAdvice'注记的类 – user7456343