JAVA开发(Spring-全局异常拦截)

全局拦截处理

快速开始
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /***
    * 参数绑定异常
    * @date 2020/08/14
    * @param exception HttpMessageNotReadableException
    */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Long> messageNotReadable(HttpMessageNotReadableException exception){
        InvalidFormatException formatException = (InvalidFormatException)exception.getCause();
        List<JsonMappingException.Reference> e = formatException.getPath();
        String fieldName = "";
        for (JsonMappingException.Reference reference :e){
            String fieldName = reference.getFieldName();
        }
        logger.error("参数不匹配"+exception);
        return Result.createFailResult(fieldName+"参数类型不匹配");
    }

    /***
    * 全局异常,如果没有匹配到上述准确的异常,都会到这里来处理
    * @date 2020/08/14
    * @param e 没有匹配到的全局异常
    */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public Result<String> all(Exception e){
        //异常信打印出来,定位bug
        logger.error("异常:",e);
        return Result.createFailResult("请稍后再试");
    }
}
@ControllerAdvice
@ControllerAdvice 默认监控所有的 @RequestMapping 方法,也可以对指定过滤的条件:
// 监控所有的被@RestController注解的Controllers类 
@ControllerAdvice(annotations = RestController.class)

// 监控特定的包下的Controllers类
@ControllerAdvice("org.example.controllers")

// 监控指定类的Controllers类
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值