在处理异常的过程中,发现Shiro在验证Token的Filter中抛出的异常无法被@ControllerAdvice处理,多番查找后 找到了如下处理方法(来源于:https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring)

  • 代码如下:
@Slf4j
@RestControllerAdvice
@Controller
public class ServiceExceptionHandler implements ErrorController {

    private static final String PATH_DEFAULT = "/error";

    // UnAuthenticationException为自定义异常 
    @ExceptionHandler(UnAuthenticationException.class)
    public Result handleUnAuthorize(UnAuthenticationException e){
        log.error("验证失败");
        return e.getResult();
    }

    @RequestMapping(PATH_DEFAULT)
    public void handleError(HttpServletRequest request) throws Throwable {
        if (request.getAttribute("javax.servlet.error.exception") != null) {
            throw (Throwable) request.getAttribute("javax.servlet.error.exception");
        }
    }

    @Override
    public String getErrorPath() {
        return PATH_DEFAULT;
    }
}
  • 原理
    异常错误会被默认重定向至/error进行处理,重写/error的Cotroller后再将异常抛出,由对应的@ExceptionHandler处理