SpringBoot中如何处理Controller之前的异常

项目中使用了shiro做权限控制,在controller上注解了@RequiresPermissions,当没有权限时,会抛出异常,但是这个异常是在拦截器中抛出的,spring boot的ControllerAdvisor无法捕捉到。

请教下,如何进行处理?


繁星coding
浏览 1873回答 2
2回答

拉风的咖菲猫

最后,是通过增加了一个HandlerInterceptor,这个方法可行,但是处理异常的地方就变成了两处,另一个是controller层异常的统一处理,总觉得不是太好的方案。@Componentpublic class PreControllerExceptionIntercep implements HandlerInterceptor {private static final Logger log = LoggerFactory.getLogger(PreControllerExceptionIntercep.class);@Overridepublic void afterCompletion(HttpServletRequest request , HttpServletResponse response,Object handler,Exception ex) throws Exception{    if(ex instanceof UnauthenticatedException){        log.info("the access isn't valid");        PackVo packVo = new PackVo();        packVo.setSuccess(false);        packVo.addMsg(BizExceptionCode.NO_PERMISSION_EXCEPTION,"");        String jsonPack = JSON.toJSONString(packVo);        response.setContentType("application/json;charset=UTF-8");        response.setHeader("Pragma","No-cache");        response.setHeader("Cache-Control","no-cache");        response.setDateHeader("Expires",0);        PrintWriter out = response.getWriter();        out.print(jsonPack);        out.flush();        out.close();    }}
打开App,查看更多内容
随时随地看视频慕课网APP