当前位置: 首页 > 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接口。

相关文章:

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

前言 在Java中处理代码运行异常是常见的技术点之一&#xff0c;我们大部分会使用封装的技巧将异常进行格式化输出&#xff0c;方便反馈给用户界面&#xff0c;也是为了代码复用 看看这行代码是怎么处理异常的 CommonExceptionType.SimpleException.throwEx("用户信息不…...

基于Redis实现短信验证码登录

目录 1 基于Session实现短信验证码登录 2 配置登录拦截器 3 配置完拦截器还需将自定义拦截器添加到SpringMVC的拦截器列表中 才能生效 4 Session集群共享问题 5 基于Redis实现短信验证码登录 6 Hash 结构与 String 结构类型的比较 7 Redis替代Session需要考虑的问题 8 …...

步入响应式编程篇(二)之Reactor API

步入响应式编程篇&#xff08;二&#xff09;之Reactor API 前言回顾响应式编程Reactor API的使用Stream引入依赖Reactor API的使用流源头的创建 reactor api的背压模式发布者与订阅者使用的线程查看弹珠图查看形成新流的日志 前言 对于响应式编程的基于概念&#xff0c;以及J…...

Oracle SQL: TRANSLATE 和 REGEXP_LIKE 的知识点详细分析

目录 前言1. TRANSLATE2. REGEXP_LIKE3. 实战 前言 &#x1f91f; 找工作&#xff0c;来万码优才&#xff1a;&#x1f449; #小程序://万码优才/r6rqmzDaXpYkJZF 1. TRANSLATE TRANSLATE 用于替换字符串中指定字符集的每个字符&#xff0c;返回替换后的字符串 逐一映射输入字…...

RabbitMQ 在实际应用时要注意的问题

1. 幂等性保障 1.1 幂等性介绍 幂等性是数学和计算机科学中某些运算的性质,它们可以被多次应⽤,⽽不会改变初始应⽤的结果. 应⽤程序的幂等性介绍 在应⽤程序中,幂等性就是指对⼀个系统进⾏重复调⽤(相同参数),不论请求多少次,这些请求对系统的影响都是相同的效果. ⽐如数据库…...

算法日记8:StarryCoding60(单调栈)

一、题目 二、解题思路&#xff1a; 题意为让我们找到每个元素的左边第一个比它小的元素&#xff0c;若不存在则输出-1 2.1法一&#xff1a;暴力&#xff08;0n2&#xff09; 首先&#xff0c;我们可以想到最朴素的算法&#xff1a;直接暴力两层for达成目标核心代码如下&…...

大象机器人发布首款穿戴式数据采集器myController S570,助力具身智能数据收集!

myController S570 具有较高的数据采集速度和远程控制能力&#xff0c;大大简化了人形机器人的编程。 myController S570 是一款可移动的轻量级外骨骼&#xff0c;具有 14 个关节、2 个操纵杆和 2 个按钮&#xff0c;它提供高数据采集速度&#xff0c;出色的兼容性&#xff0c…...

【银河麒麟高级服务器操作系统】业务访问慢网卡丢包现象分析及处理过程

了解更多银河麒麟操作系统全新产品&#xff0c;请点击访问 麒麟软件产品专区&#xff1a;product.kylinos.cn 开发者专区&#xff1a;developer.kylinos.cn 文档中心&#xff1a;document.kylinos.cn 交流论坛&#xff1a;forum.kylinos.cn 服务器环境以及配置 【内核版本…...

C语言之饭店外卖信息管理系统

&#x1f31f; 嗨&#xff0c;我是LucianaiB&#xff01; &#x1f30d; 总有人间一两风&#xff0c;填我十万八千梦。 &#x1f680; 路漫漫其修远兮&#xff0c;吾将上下而求索。 C语言之饭店外卖信息管理系统 目录 设计题目设计目的设计任务描述设计要求输入和输出要求验…...

记一次 .NET某数字化协同管理系统 内存暴涨分析

一&#xff1a;背景 1. 讲故事 高级调试训练营里的一位朋友找到我&#xff0c;说他们跑在linux上的.NET程序出现了内存泄露的情况&#xff0c;上windbg观察发现内存都是IMAGE给吃掉了&#xff0c;那些image都标记了 doublemapper__deleted_ 字样&#xff0c;问我为啥会这样&a…...

部门管理查询部门,nginx反向代理,前端如何访问到后端Tomcat 注解@RequestParam

接口开发 增删改通常是不用返回data数据&#xff0c;返回null 列表查询-结果封装&#xff0c;时间 前后端联调测试 nginx反向代理&#xff0c;前端如何访问到后端Tomcat服务器 删除部门...

JS通过ASCII码值实现随机字符串的生成(可指定长度以及解决首位不出现数值)

在之前写过一篇“JS实现随机生成字符串&#xff08;可指定长度&#xff09;”&#xff0c;当时写的过于简单和传统&#xff0c;比较粗放。此次针对此问题&#xff0c;对随机生成字符串的功能进行优化处理&#xff0c;对随机取到的字符都通过程序自动来完成。 在写之前&#xff…...

速通Docker === 快速部署Redis主从集群

目录 镜像仓库介绍 持久化你的数据库 连接到其他容器 创建自定义网络 部署主节点 部署从节点 验证部署 总结 在现代应用架构中&#xff0c;Redis作为一个高性能的内存数据库&#xff0c;被广泛应用于缓存、会话存储、实时分析等多个领域。为了提高Redis的可用性和数据的…...

论文笔记(六十三)Understanding Diffusion Models: A Unified Perspective(一)

Understanding Diffusion Models: A Unified Perspective&#xff08;一&#xff09; 文章概括引言&#xff1a;生成模型背景&#xff1a;ELBO、VAE 和分层 VAE证据下界&#xff08;Evidence Lower Bound&#xff09;变分自编码器 &#xff08;Variational Autoencoders&#x…...

stm32使用MDK5.35时遇到*** TOOLS.INI: TOOLCHAIN NOT INSTALLED

mdk5.35出现*** TOOLS.INI: TOOLCHAIN NOT INSTALLED的问题&#xff01;&#xff01;&#xff01;&#xff01; 以管理员身份重新打开MDK5.35.0.0&#xff0c;用keygen破解密码&#xff0c;但是一直提示我是没有破解成功。 解决办法&#xff1a; target 改成ARM...

在Ubuntu上安装RabbitMQ教程

1、安装erlang 因为rabbitmq是基于erlang开发的&#xff0c;所以要安装rabbitmq&#xff0c;首先需要安装erlang运行环境 apt-get install erlang执行命令查是否安装成功&#xff1a;erl&#xff0c;疯狂 Ctrlc 就能退出命令行 2、安装rabbitmq 1、查看erlang与rabbitmq版本…...

【算法】集合List和队列

阿华代码&#xff0c;不是逆风&#xff0c;就是我疯 你们的点赞收藏是我前进最大的动力&#xff01;&#xff01; 希望本文内容能够帮助到你&#xff01;&#xff01; 目录 零&#xff1a;集合&#xff0c;队列的用法 一&#xff1a;字母异位词分组 二&#xff1a;二叉树的锯…...

uniapps使用HTML5的io模块拷贝文件目录

最近在集成sqlite到uniapp的过程中&#xff0c;因为要将sqlite数据库预加载&#xff0c;所以需要使用HTML5的plus.io模块。使用过程中遇到了许多问题&#xff0c;比如文件路径总是解析不到等。尤其是应用私有文档目录’_doc’。 根据官方文档&#xff1a; 为了安全管理应用的…...

css‘s hover VS mobile

.animation {animation: 30s move infinite linear;/* &:hover {animation-play-state: paused;*/ }原本写的好好的&#xff0c;测试说&#xff1a;“移动端点击滚动条&#xff0c;跳转到其他页面后&#xff0c;返回当前页面&#xff0c;滚动条不滚动&#xff1b;可以优化位…...

工业制造离不开的BOM

在制造业的浩瀚星空中&#xff0c;物料清单&#xff08;BOM&#xff09;犹如“北极星”&#xff0c;牢牢指引着产品从设计蓝图迈向实物诞生的全过程。 BOM的分类 按照设计制造的不同阶段&#xff0c;将BOM划分为设计BOM、工艺BOM、制造BOM三种类型。 设计BOM Engineering BO…...

C++实现分布式网络通信框架RPC(3)--rpc调用端

目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中&#xff0c;我们已经大致实现了rpc服务端的各项功能代…...

(二)TensorRT-LLM | 模型导出(v0.20.0rc3)

0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述&#xff0c;后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作&#xff0c;其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...

Robots.txt 文件

什么是robots.txt&#xff1f; robots.txt 是一个位于网站根目录下的文本文件&#xff08;如&#xff1a;https://example.com/robots.txt&#xff09;&#xff0c;它用于指导网络爬虫&#xff08;如搜索引擎的蜘蛛程序&#xff09;如何抓取该网站的内容。这个文件遵循 Robots…...

LLM基础1_语言模型如何处理文本

基于GitHub项目&#xff1a;https://github.com/datawhalechina/llms-from-scratch-cn 工具介绍 tiktoken&#xff1a;OpenAI开发的专业"分词器" torch&#xff1a;Facebook开发的强力计算引擎&#xff0c;相当于超级计算器 理解词嵌入&#xff1a;给词语画"…...

Java入门学习详细版(一)

大家好&#xff0c;Java 学习是一个系统学习的过程&#xff0c;核心原则就是“理论 实践 坚持”&#xff0c;并且需循序渐进&#xff0c;不可过于着急&#xff0c;本篇文章推出的这份详细入门学习资料将带大家从零基础开始&#xff0c;逐步掌握 Java 的核心概念和编程技能。 …...

Caliper 配置文件解析:config.yaml

Caliper 是一个区块链性能基准测试工具,用于评估不同区块链平台的性能。下面我将详细解释你提供的 fisco-bcos.json 文件结构,并说明它与 config.yaml 文件的关系。 fisco-bcos.json 文件解析 这个文件是针对 FISCO-BCOS 区块链网络的 Caliper 配置文件,主要包含以下几个部…...

【Go语言基础【13】】函数、闭包、方法

文章目录 零、概述一、函数基础1、函数基础概念2、参数传递机制3、返回值特性3.1. 多返回值3.2. 命名返回值3.3. 错误处理 二、函数类型与高阶函数1. 函数类型定义2. 高阶函数&#xff08;函数作为参数、返回值&#xff09; 三、匿名函数与闭包1. 匿名函数&#xff08;Lambda函…...

NPOI Excel用OLE对象的形式插入文件附件以及插入图片

static void Main(string[] args) {XlsWithObjData();Console.WriteLine("输出完成"); }static void XlsWithObjData() {// 创建工作簿和单元格,只有HSSFWorkbook,XSSFWorkbook不可以HSSFWorkbook workbook new HSSFWorkbook();HSSFSheet sheet (HSSFSheet)workboo…...

【Linux】自动化构建-Make/Makefile

前言 上文我们讲到了Linux中的编译器gcc/g 【Linux】编译器gcc/g及其库的详细介绍-CSDN博客 本来我们将一个对于编译来说很重要的工具&#xff1a;make/makfile 1.背景 在一个工程中源文件不计其数&#xff0c;其按类型、功能、模块分别放在若干个目录中&#xff0c;mak…...

热门Chrome扩展程序存在明文传输风险,用户隐私安全受威胁

赛门铁克威胁猎手团队最新报告披露&#xff0c;数款拥有数百万活跃用户的Chrome扩展程序正在通过未加密的HTTP连接静默泄露用户敏感数据&#xff0c;严重威胁用户隐私安全。 知名扩展程序存在明文传输风险 尽管宣称提供安全浏览、数据分析或便捷界面等功能&#xff0c;但SEMR…...