用枚举来处理java自定义异常
2017-12-26 17:22
525 查看
在系统开发过程中,总少不免要自己处理一些异常信息,然后将异常信息变成友好的提示返回到客户端的这样一个过程,之前都是new一个自定义的异常,当然这个所谓的自定义异常也是继承RuntimeException的,但这样往往会造成异常信息说明不一致的情况,所以就想到了用枚举来解决的办法。
1、先创建一个接口,里面提供两个方法,一个是getErrorCode, 一个是getErrorMessage,如:
2、创建一个枚举,实现IErrorCode里的方法
3、定义一个自定义的异常类
4、代码中抛异常
5、可以通过异常拦截器来拦截错误,获取错误后统一格式输出;
这样做的好处是可以高度统一所有异常返回的code及message, 如果需要更改提示信息或代号,只需更改SysErrorEnums即可,并且可以自行添加多个异常枚举文件来分别对应不同的模板异常信息。代码结构简单,清淅。
1、先创建一个接口,里面提供两个方法,一个是getErrorCode, 一个是getErrorMessage,如:
public interface IErrorCode { public String getErrorCode(); public String 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例程练习(自定义异常处理)
- Java自定义异常(优雅的处理异常)
- java异常处理之自定义异常类(转)
- java例程练习(自定义异常处理)
- java例程练习(自定义异常处理)
- 通俗易懂详解java的异常处理及自定义异常类型
- java异常的学习和理解(包含异常的处理方式,异常的分类,运行时异常和编译时异常,自定义异常)
- Java学习笔记之异常、处理异常、异常抛出、自定义异常、异常链
- 牛客网Java刷题知识点之什么是异常、异常处理的原理是什么、为什么要使用异常、异常体系、运行时异常、普通异常、自定义异常、异常链
- java例程练习(自定义异常处理)
- 在java Spring基础上实现自定义异常处理框架教程
- java异常处理和自定义异常利用try和catch让程序继续下去(回来自己再写个例子试运行下)
- java自定义异常配合枚举
- 黑马程序员 Java基础 处理异常信息以及自定义异常
- Java中的异常处理(三) - 自定义异常处理
- Java自学笔记(第十天)-异常-异常的处理-throws-throw-多异常处理-自定义异常-throwable类-RunTimeException类-finally-异常在方法继承中的注意事项-
- 在java Spring基础上实现自定义异常处理框架教程