当前位置: 首页 > news >正文

【Java】Java抛异常到用户界面公共封装

前言

在Java中处理代码运行异常是常见的技术点之一,我们大部分会使用封装的技巧将异常进行格式化输出,方便反馈给用户界面,也是为了代码复用

看看这行代码是怎么处理异常的

CommonExceptionType.SimpleException.throwEx("用户信息不能为空");

1、首先CommonExceptionType是一个枚举类型

public enum CommonExceptionType implements IExceptionType {

   CommonException(),
    SimpleException(-1, "%s", CommonException),

主要的实现还是这个接口:IExceptionType

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public interface IExceptionType {
    IExceptionType getParent();

    Integer getErrorCode();

    String getErrorInfoFormat();

    static final ExceptionConsumer consumerLocal = new ExceptionConsumer();

    default IExceptionType initConsumer(Consumer<Exception> consumer) {
        consumerLocal.get().add(consumer);
        return this;
    }
    default IExceptionType initConsumer() {
        consumerLocal.get().add(null);
        return this;
    }

    default RuntimeException throwEx(Object... args) {
        return throwEx((Exception) null, args);
    }

    default RuntimeException throwEx(Throwable e, Object... args) {
        String exceptionInfo = getErrorInfoFormat();
        Integer errorCode = getErrorCode();

        if (args != null && args.length > 0) {
            exceptionInfo = String.format(getErrorInfoFormat(), args);
        }

        CommonException ex;
        if (e == null) {
            ex = new CommonException(exceptionInfo);
        } else {
            try {
                ex = new CommonException(e, exceptionInfo, e.getMessage());
            } catch (Exception exc) {
                ex = new CommonException(e, "%s", e.getMessage());
            }
        }

        ex.setErrorCode(errorCode);
        ex.setExceptionType(this);

        throw ex;
    }
    default <T extends Exception> boolean catchEx(Throwable ex) {
        return catchEx(ex,null);
    }


    default <T extends Exception> boolean catchEx(Throwable ex, Consumer<T> callback) {
        if (ex instanceof CommonException) {
            IExceptionType ce = ((CommonException) ex).getExceptionType();
            if (this.equals(ce) || this.isParent(ce)) {
                if (callback != null) {
                    callback.accept((T) ex);
                }
                return true;
            }
        }
        if (this == CommonExceptionType.CommonException && ex instanceof sunbox.core.exception.CommonException) {
            if (callback != null) {
                callback.accept((T) ex);
            }
            return true;
        }
        if (this == CommonExceptionType.Finally) {
            if (callback != null) {
                callback.accept((T) ex);
            }
            return true;
        }
        return false;
    }
    default boolean isParent(sunbox.core.exception.CommonException ex) {
        if (ex instanceof CommonException) {
            IExceptionType ce = ((CommonException) ex).getExceptionType();
            if (this.equals(ce) || this.isParent(ce)) {
                return true;
            }
        }
        return false;
    }
    default boolean isParent(IExceptionType et) {
        IExceptionType parent = et;
        while (parent != null) {
            if (parent.equals(this)) {
                return true;
            }
            parent = parent.getParent();
        }
        return false;
    }

    default <R, T extends Exception> R tryCatch(Supplier<R> func, Function<T, R> catchFunc) {
        Exception ex = null;
        try {
            if (func != null) {
                return func.get();
            }
            return null;
        } catch (Exception e) {
            if (this.catchEx(e, null)) {
                if (catchFunc != null) {
                    return catchFunc.apply((T) e);
                }
                return null;
            }
            throw e;
        }
    }

    class CommonException extends sunbox.core.exception.CommonException {
        private IExceptionType exceptionType;

        protected CommonException() {
            super("系统异常");
            errorInfo = "系统异常";
        }

        protected CommonException(String errorInfo) {
            super(errorInfo);
            this.errorInfo=errorInfo;
        }

        protected CommonException(String format, Object... args) {
            super(String.format(format, args));
            errorInfo = String.format(format, args);
        }

        protected CommonException(Throwable e, String format, Object... args) {
            super(e, String.format(format, args));
            errorInfo = String.format(format, args);
        }

        protected CommonException(Exception e) {
            super(e);
            errorInfo = "系统异常";
        }

        public IExceptionType getExceptionType() {
            return exceptionType;
        }

        public void setExceptionType(IExceptionType exceptionType) {
            this.exceptionType = exceptionType;
            setErrorCode(exceptionType.getErrorCode());
        }
    }
}
 

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;public interface IExceptionType {IExceptionType getParent();Integer getErrorCode();String getErrorInfoFormat();static final ExceptionConsumer consumerLocal = new ExceptionConsumer();default IExceptionType initConsumer(Consumer<Exception> consumer) {consumerLocal.get().add(consumer);return this;}default IExceptionType initConsumer() {consumerLocal.get().add(null);return this;}default RuntimeException throwEx(Object... args) {return throwEx((Exception) null, args);}default RuntimeException throwEx(Throwable e, Object... args) {String exceptionInfo = getErrorInfoFormat();Integer errorCode = getErrorCode();if (args != null && args.length > 0) {exceptionInfo = String.format(getErrorInfoFormat(), args);}CommonException ex;if (e == null) {ex = new CommonException(exceptionInfo);} else {try {ex = new CommonException(e, exceptionInfo, e.getMessage());} catch (Exception exc) {ex = new CommonException(e, "%s", e.getMessage());}}ex.setErrorCode(errorCode);ex.setExceptionType(this);throw ex;}default <T extends Exception> boolean catchEx(Throwable ex) {return catchEx(ex,null);}default <T extends Exception> boolean catchEx(Throwable ex, Consumer<T> callback) {if (ex instanceof CommonException) {IExceptionType ce = ((CommonException) ex).getExceptionType();if (this.equals(ce) || this.isParent(ce)) {if (callback != null) {callback.accept((T) ex);}return true;}}if (this == CommonExceptionType.CommonException && ex instanceof sunbox.core.exception.CommonException) {if (callback != null) {callback.accept((T) ex);}return true;}if (this == CommonExceptionType.Finally) {if (callback != null) {callback.accept((T) ex);}return true;}return false;}default boolean isParent(sunbox.core.exception.CommonException ex) {if (ex instanceof CommonException) {IExceptionType ce = ((CommonException) ex).getExceptionType();if (this.equals(ce) || this.isParent(ce)) {return true;}}return false;}default boolean isParent(IExceptionType et) {IExceptionType parent = et;while (parent != null) {if (parent.equals(this)) {return true;}parent = parent.getParent();}return false;}default <R, T extends Exception> R tryCatch(Supplier<R> func, Function<T, R> catchFunc) {Exception ex = null;try {if (func != null) {return func.get();}return null;} catch (Exception e) {if (this.catchEx(e, null)) {if (catchFunc != null) {return catchFunc.apply((T) e);}return null;}throw e;}}class CommonException extends sunbox.core.exception.CommonException {private IExceptionType exceptionType;protected CommonException() {super("系统异常");errorInfo = "系统异常";}protected CommonException(String errorInfo) {super(errorInfo);this.errorInfo=errorInfo;}protected CommonException(String format, Object... args) {super(String.format(format, args));errorInfo = String.format(format, args);}protected CommonException(Throwable e, String format, Object... args) {super(e, String.format(format, args));errorInfo = String.format(format, args);}protected CommonException(Exception e) {super(e);errorInfo = "系统异常";}public IExceptionType getExceptionType() {return exceptionType;}public void setExceptionType(IExceptionType exceptionType) {this.exceptionType = exceptionType;setErrorCode(exceptionType.getErrorCode());}}
}

这里我们可以看到interface里面,不再是单纯函数的定义,还有函数的实现。这是要转变。这样使接口的实现多了一份灵活性,但是如果接口里单纯的只定义函数,没有函数的实现的话,可能代码逻辑和结构更加清晰一些,这也是过去我们学习的interface接口。

http://www.lryc.cn/news/524713.html

相关文章:

  • 基于Redis实现短信验证码登录
  • 步入响应式编程篇(二)之Reactor API
  • Oracle SQL: TRANSLATE 和 REGEXP_LIKE 的知识点详细分析
  • RabbitMQ 在实际应用时要注意的问题
  • 算法日记8:StarryCoding60(单调栈)
  • 大象机器人发布首款穿戴式数据采集器myController S570,助力具身智能数据收集!
  • 【银河麒麟高级服务器操作系统】业务访问慢网卡丢包现象分析及处理过程
  • C语言之饭店外卖信息管理系统
  • 记一次 .NET某数字化协同管理系统 内存暴涨分析
  • 部门管理查询部门,nginx反向代理,前端如何访问到后端Tomcat 注解@RequestParam
  • JS通过ASCII码值实现随机字符串的生成(可指定长度以及解决首位不出现数值)
  • 速通Docker === 快速部署Redis主从集群
  • 论文笔记(六十三)Understanding Diffusion Models: A Unified Perspective(一)
  • stm32使用MDK5.35时遇到*** TOOLS.INI: TOOLCHAIN NOT INSTALLED
  • 在Ubuntu上安装RabbitMQ教程
  • 【算法】集合List和队列
  • uniapps使用HTML5的io模块拷贝文件目录
  • css‘s hover VS mobile
  • 工业制造离不开的BOM
  • HTML中的`<!DOCTYPE html>`是什么意思?
  • C语言之斗地主游戏
  • 【玩转全栈】----Django制作部门管理页面
  • Unreal Engine 5 C++ Advanced Action RPG 十章笔记
  • 学习ASP.NET Core的身份认证(基于JwtBearer的身份认证9)
  • 缓存之美:万文详解 Caffeine 实现原理(上)
  • Spark/Kafka
  • 深入浅出:Go语言中的Unicode与字符编码详解
  • 什么是SSL及SSL的工作流程
  • .Net Core微服务入门全纪录(二)——Consul-服务注册与发现(上)
  • AD7606, 逐次逼近型ADC以及一次被GPT坑了的过程.