美文网首页
EL-Admin框架-异常处理模块

EL-Admin框架-异常处理模块

作者: SmileFH | 来源:发表于2021-01-28 16:59 被阅读0次

一、common模块下me.zhengjie.exception包(异常处理)中类的解读

me.zhengjie.exception包下的类

总体上是用类似策略模式的自定义的异常,借全局异常处理器,根据抛出的异常类分别去处理抛出的不同异常。

1.类似策略模式的自定义异常类解读

①me.zhengjie.exception.BadConfigurationException(配置异常)类,继承java.lang.RuntimeException类(用来在程序中抛出配置异常通知)

整个类继承复制java.lang.RuntimeException类,只是改了方法名字

public class BadConfigurationException extends RuntimeException {
    /**
     * Constructs a new runtime exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link `#initCause}`.
     */
    public BadConfigurationException() {
        super();
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param message the detail message. The detail message is saved for
     *                later retrieval by the {@link #getMessage()} method.
     */
    public BadConfigurationException(String message) {
        super(message);
    }

    /**
     * Constructs a new runtime exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * {@code cause} is <i>not</i> automatically incorporated in
     * this runtime exception's detail message.
     *
     * @param message the detail message (which is saved for later retrieval
     *                by the {@link #getMessage()} method).
     * @param cause   the cause (which is saved for later retrieval by the
     *                {@link #getCause()} method).  (A {@code null} value is
     *                permitted, and indicates that the cause is nonexistent or
     *                unknown.)
     * @since 1.4
     */
    public BadConfigurationException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new runtime exception with the specified cause and a
     * detail message of {@code (cause==null ? null : cause.toString())}
     * (which typically contains the class and detail message of
     * {@code cause}).  This constructor is useful for runtime exceptions
     * that are little more than wrappers for other throwables.
     *
     * @param cause the cause (which is saved for later retrieval by the
     *              {@link #getCause()} method).  (A {@code null} value is
     *              permitted, and indicates that the cause is nonexistent or
     *              unknown.)
     * @since 1.4
     */
    public BadConfigurationException(Throwable cause) {
        super(cause);
    }

    /**
     * Constructs a new runtime exception with the specified detail
     * message, cause, suppression enabled or disabled, and writable
     * stack trace enabled or disabled.
     *
     * @param message            the detail message.
     * @param cause              the cause.  (A {@code null} value is permitted,
     *                           and indicates that the cause is nonexistent or unknown.)
     * @param enableSuppression  whether or not suppression is enabled
     *                           or disabled
     * @param writableStackTrace whether or not the stack trace should
     *                           be writable
     * @since 1.7
     */
    protected BadConfigurationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

②me.zhengjie.exception.BadRequestException(错误请求异常)类继承java.lang.RuntimeException类

// lombok中为成员变量生成get方法的注解
@Getter
public class BadRequestException extends RuntimeException{

    private Integer status = BAD_REQUEST.value();

    public BadRequestException(String msg){
        // 调用父类中的单参数构造方法
        super(msg);
    }

    public BadRequestException(HttpStatus status,String msg){
        // 调用父类中的单参数构造方法
        super(msg);
        // 给请求异常中的状态码赋值
        this.status = status.value();
    }
}

③me.zhengjie.exception.EntityExistException(实体类已经存在异常)类继承java.lang.RuntimeException类

public class EntityExistException extends RuntimeException {

    public EntityExistException(Class clazz, String field, String val) {
        // 把拼接好的内容作为参数调用父类的方法
        super(EntityExistException.generateMessage(clazz.getSimpleName(), field, val));
    }

    private static String generateMessage(String entity, String field, String val) {
        // 首字母大写并手动拼接需要的内容
        return StringUtils.capitalize(entity)
                + " with " + field + " "+ val + " existed";
    }
}

④me.zhengjie.exception.EntityNotFoundException(实体不存在异常类)继承java.lang.RuntimeException类

public class EntityNotFoundException extends RuntimeException {

    public EntityNotFoundException(Class clazz, String field, String val) {
        // 调用类的getSimpleName()方法得到类的简写
        // 作为String参数调用父类中的单参数构造方法
        super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), field, val));
    }

    private static String generateMessage(String entity, String field, String val) {
        // 首字母大写并手动拼接所需字符串
        return StringUtils.capitalize(entity)
                + " with " + field + " "+ val + " does not exist";
    }
}

2. 全局异常处理配置类

①me.zhengjie.exception.handler.GlobalExceptionHandler(全局异常处理器)

其中涉及到了me.zhengjie.utils.ThrowableUtil#getStackTrace()自定义异常堆栈信息获取方法,me.zhengjie.exception.handler.ApiError返回给前端的API错误信息类

// 日志注解
@Slf4j
// 映射注解增强器[详情戳这里了解](https://www.cnblogs.com/UncleWang001/p/10949318.html)
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理所有不可知的异常
     */
    // 异常处理器注解
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<ApiError> handleException(Throwable e){
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        return buildResponseEntity(ApiError.error(e.getMessage()));
    }

    /**
     * BadCredentialsException
     */
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){
        // 打印堆栈信息
        String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage();
        log.error(message);
        return buildResponseEntity(ApiError.error(message));
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = BadRequestException.class)
    public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage()));
    }

    /**
     * 处理 EntityExist
     */
    @ExceptionHandler(value = EntityExistException.class)
    public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        return buildResponseEntity(ApiError.error(e.getMessage()));
    }

    /**
     * 处理 EntityNotFound
     */
    @ExceptionHandler(value = EntityNotFoundException.class)
    public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage()));
    }

    /**
     * 处理所有接口数据验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        // 打印堆栈信息
        log.error(ThrowableUtil.getStackTrace(e));
        String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        String msg = "不能为空";
        if(msg.equals(message)){
            message = str[1] + ":" + message;
        }
        return buildResponseEntity(ApiError.error(message));
    }

    /**
     * 统一返回
     */
    private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
        return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
    }
}

②me.zhengjie.exception.handler.ApiError类(返回给前端的响应体内容对象)

// lombok中生成类中get/set方法,equls方法,hashcode方法,tostring方法,空参构造的注解
@Data
class ApiError {

    // 返回的默认HTTP状态码
    private Integer status = 400;
    // 后端日期时间格式转换成json格式的注解
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    // 当前时间的时间戳
    private LocalDateTime timestamp;
    // API异常携带的信息
    private String message;

    private ApiError() {
        timestamp = LocalDateTime.now();
    }

    /**
     * 静态默认响应状态码构造方法,方便调用
     *
     * @author Hue Fu
     * @param message java.lang.String
     * @return me.zhengjie.exception.handler.ApiError
     * @date 2021-01-28 14:13
     * @since 0.0.1
     */
    public static ApiError error(String message){
        ApiError apiError = new ApiError();
        apiError.setMessage(message);
        return apiError;
    }

    /**
     * 自定义默认响应信息(状态码和携带信息)构造方法
     *
     * @author Hue Fu
     * @param status java.lang.Integer
     * @param message java.lang.String
     * @return me.zhengjie.exception.handler.ApiError
     * @date 2021-01-28 14:14
     * @since 0.0.1
     */
    public static ApiError error(Integer status, String message){
        ApiError apiError = new ApiError();
        apiError.setStatus(status);
        apiError.setMessage(message);
        return apiError;
    }
}

到现在为止我们把EL-Admin框架中的异常处理的所有类都梳理了一遍。其中起主要作用的是me.zhengjie.exception.handler.GlobalExceptionHandler这个全局异常处理类,通过它,我们实现了对服务器端API中异常的全局性管理。在这个类中起主要作用的代码是@RestControllerAdvice和@ExceptionHandler这两个注解,没有@RestControllerAdvice这个注解我们无法对每个API进行增强映射建议,没有@ExceptionHandler注解我们没法对特殊的异常类做自定义化操作。
当然也许其中你也有其他的问题

  1. 为啥自定义异常都继承了java.lang.RuntimeException类而不是继承最初的异常类呢?

    继承不继承不是这么说的

  2. @JsonFormat和@DateTimeFormat的区别是啥?

    @JsonFormat和@DateTimeFormat的区别

  3. @ExceptionHandler注解的作用是啥?

    使用@ControllerAdvice + @ExceptionHandler 注解实现Controller层异常全局处理_Abysscarry的博客-CSDN博客

  4. me.zhengjie.utils.ThrowableUtil工具类中java.io.StringWriter类是啥?

    要说他我们需要先说一下java中的异常输出方式, 有两种抛出的方式,一种是我们常用的System.out标准输出流打印,另外一种是Throwable本身具有的方法e.printStackTrace()打印出更深层的信息。但有时候仅仅输出到控制台是不够的,我们往往都希望把异常给写入到数据库或者文件中去。所以这种时候就需要我们的java.io.StringWriter出场了,用它创建一个输入流,先把异常给输出了,还是上边的那个方法,不过不同的是,它有好几个构造方法,这次我们调用有参构造StringWriter/PrintWriter在Java输出异常信息中的作用 - Evil_XJZ - 博客园。既然是IO流当然需要我们去手动关闭一下啦,在java7之前我们还是用老一套的try,catch,finally,但是在java7的时候出现了一个语法糖[利用try-with-resource机制关闭连接_白白胖胖充满希望-CSDN博客]

相关文章

网友评论

      本文标题:EL-Admin框架-异常处理模块

      本文链接:https://www.haomeiwen.com/subject/kuqttltx.html