用枚举来处理java自定义异常
2018-03-13 13:17
585 查看
在系统开发过程中,总少不免要自己处理一些异常信息,然后将异常信息变成友好的提示返回到客户端的这样一个过程,之前都是new一个自定义的异常,当然这个所谓的自定义异常也是继承RuntimeException的,但这样往往会造成异常信息说明不一致的情况,所以就想到了用枚举来解决的办法。
1、先创建一个接口,里面提供两个方法,一个是getErrorCode, 一个是getErrorMessage,如:
?
2、创建一个枚举,实现IErrorCode里的方法
3、定义一个自定义的异常类
4、代码中抛异常
5、可以通过异常拦截器来拦截错误,获取错误后统一格式输出;
这样做的好处是可以高度统一所有异常返回的code及message, 如果需要更改提示信息或代号,只需更改SysErrorEnums即可,并且可以自行添加多个异常枚举文件来分别对应不同的模板异常信息。代码结构简单,清淅。
1、先创建一个接口,里面提供两个方法,一个是getErrorCode, 一个是getErrorMessage,如:
?
2、创建一个枚举,实现IErrorCode里的方法
public enum SysErrorEnums implements IErrorCode { /**参数为空*/ EMPTY_PARAME("A11002","参数为空"), /**参数错误*/ ERROR_PARAME("A11002","参数错误"); private String errorCode; private String errorMessage; private SysErrorEnums(String errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
3、定义一个自定义的异常类
public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; private IErrorCode iErrorCode; private String errorCode; private String errorMessage; private Map<String, Object> errorData; public BusinessException(IErrorCode iErrorCode) { super(); this.iErrorCode = iErrorCode; this.errorCode = iErrorCode.getErrorCode(); this.errorMessage = iErrorCode.getErrorMessage(); } //其他get、set、构造方法}
4、代码中抛异常
if(true){ throw new BusinessException(SysErrorEnums.EMPTY_OBJ); }
5、可以通过异常拦截器来拦截错误,获取错误后统一格式输出;
这样做的好处是可以高度统一所有异常返回的code及message, 如果需要更改提示信息或代号,只需更改SysErrorEnums即可,并且可以自行添加多个异常枚举文件来分别对应不同的模板异常信息。代码结构简单,清淅。
相关文章推荐
- 用枚举来处理java自定义异常
- (转)用枚举来处理java自定义异常
- Java异常处理--自定义异常
- java异常处理之自定义异常类
- Think in Java 笔记_Chapter12_1_Exception基础_异常处理3_自定义异常以及抛出多个异常的处理
- Java自学笔记(第十天)-异常-异常的处理-throws-throw-多异常处理-自定义异常-throwable类-RunTimeException类-finally-异常在方法继承中的注意事项-
- java异常处理和自定义异常利用try和catch让程序继续下去
- java异常处理之自定义异常类
- 牛客网Java刷题知识点之什么是异常、异常处理的原理是什么、为什么要使用异常、异常体系、运行时异常、普通异常、自定义异常、异常链
- Java异常处理:Part3 自定义异常
- java编译期的异常处理和自定义异常
- JAVA之旅(十)——异常的概述,Try-Catch,异常声明Throws,多异常处理,自定义异常,Throw和Throws的区别
- java4Android(12)java中的异常(13)自定义异常,异常处理的两种方式
- 在java Spring基础上实现自定义异常处理框架教程
- java异常处理的简单实例和解释,自定义一个异常类
- JAVA之旅(十)——异常的概述,Try-Catch,异常声明Throws,多异常处理,自定义异常,Throw和Throws的区别
- JAVA基础再回首(十九)——异常的概述、Try…Catch、多异常处理、Throws、throw、finally、自定义异常及异常的注意事项
- Java中自定义异常的两种处理方法
- 通俗易懂详解java的异常处理及自定义异常类型
- SpringBoot07 异常枚举、自定义异常、统一的全局异常处理