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

本文分享了一种统一异常处理的实现方法,通过自定义异常处理器来捕获并处理Controller中的各种异常,包括业务异常、非法参数及HTTP消息不可读等。然而,对于Filter中的异常处理仍存在难题,文中提出了一种直接输出错误信息至浏览器的解决方案,并寻求更优雅的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

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

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

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

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

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

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

        R<String> response = R.<String> 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<String, String> 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中异常的方法!

评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值