Springboot 自定义异常

65 阅读1分钟

这篇文章主要讲述两点:

  1. 如何自定义异常,并如何使用
  2. 如何简单统一的格式化字符串,使其作为日志信息,方便定位问题、解决问题

1. 自定义异常

  • 自定义异常类
package com.example.testspring.user.exception;

public class UserException extends RuntimeException{
    public UserException(String msg){
        super(msg);
    }

    public UserException(String msg, Throwable e){
        super(msg, e);
    }
} 
  • 使用自定义异常
try {
    if (user.getId().equals(1L)) {
        throw new UserException("throw new UserException!!!");
    } else if (user.getId().equals(2L)) {
        throw new Exception("throw new Exception");
    }

} catch (UserException e) {
    log.error("fdsfs", e);
} catch (Exception e) {
    log.error("this is in exception", e);
}

2. 格式化字符串

  • 那么如何将定位问题需要的关键信息,展示在日志里面呢? 很简单,使用slf4j 里面的 MessageFormatter 类
try {
    if (user.getId().equals(1L)) {
        throw new UserException("throw new UserException!!!");
    } else if (user.getId().equals(2L)) {
        throw new Exception("throw new Exception");
    }
} catch (UserException e) {
    String msg = MessageFormatter
            .format("this exception className: {}", UserException.class)
            .getMessage();
    log.error(msg, e);
} catch (Exception e) {
    log.error("this is in exception", e);
}

这里要注意两点

    1. MessageFormatter 的占位符和 log.info 一样,都是 {}
    1. MessageFormatter.format 之后还需要 getMessage 才能获取最终的字符串