SpringBoot统一异常拦截处理(filter中的异常无法被拦截处理)

统一异常的拦截处理,网上也是很多资料了,这里贴一下我的异常处理代码

@Slf4j
@RestControllerAdvice( annotations = RestController.class )
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler( BizException.class )
    public ResponseEntity> otherException( BizException e ) {
        log.error( "业务异常: {}", e );

        R response = R. builder()
                              .code( RCode.ERROR.getCode() )
                              .msg( e.getMessage() )
                              .build();

        return new ResponseEntity<>( response, HttpStatus.OK );
    }

    @ExceptionHandler( IllegalArgumentException.class )
    public ResponseEntity> otherException( IllegalArgumentException e ) {
        log.warn( "非法参数:{}", e );

        R response = R. builder()
                              .code( RCode.INVALID_PARAM.getCode() )
                              .msg( e.getMessage() )
                              .build();

        return new ResponseEntity<>( response, HttpStatus.OK );
    }

    @Override
    protected ResponseEntity handleHttpMessageNotReadable( HttpMessageNotReadableException ex,
                                                                   HttpHeaders headers, HttpStatus status,
                                                                   WebRequest request ) {
        log.warn( "内部错误:{}", ex.getMessage(), ex );

        R response = R. builder()
                              .code( RCode.ERROR.getCode() )
                              .msg( ex.getMessage() )
                              .build();

        return new ResponseEntity<>( response, HttpStatus.INTERNAL_SERVER_ERROR );
    }
} 
  

但是,这个异常处理只能够处理controller中的异常,对于filter中的异常无法捕获,所以我在网上也找了一些,基本上都是继承抽象类或者实现一些接口,比如BasicErrorController/ErrorController,我尝试了一下,未能解决我自己的问题,还是无法拦截filter中的异常,所以我在最后不得已而为之,用了一个不是办法的办法:

那就是直接在filter中将错误信息和错误状态码输出到浏览器,我直接不经过异常处理器,也没有处理异常,而是直接把我想告诉浏览器的信息直接输出.代码如下:

@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		
		if (!fasle) {
			Map map = new HashMap<>();
			map.put("code", "9999");
			map.put("msg", "没有访问权限,如需要访问,请联系管理员!");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(JSONObject.toJSON(map));
			return;
		}

		filterChain.doFilter(servletRequest, servletResponse);
		return;
	}

以上完全是抖机灵的做法,还请大佬指点一个能够捕获这个filter中异常的方法!

你可能感兴趣的:(学习,java,springcloud,filter)