How to handle exceptions before Controller in SpringBoot

shiro is used as permission control in the project, and @ RequiresPermissions, is annotated on controller. If there is no permission, an exception will be thrown, but this exception cannot be caught by the ControllerAdvisor of, spring boot thrown in the interceptor.

how to deal with it?

Mar.18,2021

I don't quite understand exactly what you want to do, but if you want a unified exception catch class, I can give you an idea. Spring can achieve this effect through annotations and xml. Look at your style should be more accustomed to annotations, then I will talk about simple Ex throwing processing, first create a MyExceptionAdviceHandler class, plus @ ControllerAdvice annotation, this annotation is an enhancement to the controller, acting on all RequestMapping annotations (in the case of no specific package specified), and then declare a processException method with an Exception parameter ex, that needs to catch exceptions to the controller and therefore requires @ ExceptionHandler, At the same time, I suggest adding a @ ResponseBody annotation to make it a little more friendly. Then declare an ApiResponse object and inject an ex exception into it and return, so that a generic capture class is written. Let me write a sample code. If there is something wrong, you are welcome to correct it.
`

@ControllerAdivce
public class MyExceptionHandler{
    @ResponseBody
    @ExceptionHandler
    public ApiResponse processEx(Exception ex){
        ApiResponse resp = ApiResponse.responseError(ex);
        return resp;
    }
}

`


finally, this method is feasible by adding a HandlerInterceptor, but the handling of exceptions becomes two places, and the other is the unified handling of exceptions in the controller layer, which always feels that it is not a good solution.

@ Component
public class PreControllerExceptionIntercep implements HandlerInterceptor {

private static final Logger log = LoggerFactory.getLogger(PreControllerExceptionIntercep.class);
@Override
public 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();
    }

}

}


https://blog.csdn.net/L_Sail/.

Menu