当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot如何优雅的处理全局异常

SpringBoot如何优雅的处理全局异常

2019年07月19日  | 移动技术网IT编程  | 我要评论
前言 本篇文章主要介绍的是springboot项目进行全局异常的处理。 springboot全局异常准备 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工

前言

本篇文章主要介绍的是springboot项目进行全局异常的处理。

springboot全局异常准备

说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码。

开发准备

环境要求

jdk:1.8

springboot:1.5.17.release

首先还是maven的相关依赖:

 <properties>
 <project.build.sourceencoding>utf-8</project.build.sourceencoding>
 <java.version>1.8</java.version>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
 </properties>
 <parent>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-parent</artifactid>
 <version>1.5.17.release</version>
 <relativepath />
 </parent>
 <dependencies>
 <!-- spring boot web 依赖 核心 -->
 <dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-web</artifactid>
 </dependency>
 <!-- spring boot test 依赖 -->
 <dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-test</artifactid>
  <scope>test</scope>
 </dependency>

 <dependency>
  <groupid>com.alibaba</groupid>
  <artifactid>fastjson</artifactid>
  <version>1.2.41</version>
 </dependency>
 </dependencies>

配置文件这块基本不需要更改,全局异常的处理只需在代码中实现即可。

代码编写

springboot的项目已经对有一定的异常处理了,但是对于我们开发者而言可能就不太合适了,因此我们需要对这些异常进行统一的捕获并处理。springboot中有一个controlleradvice的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用exceptionhandler注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。

我们根据下面的这个示例来看该注解是如何使用吧。

示例代码:

@controlleradvice
public class myexceptionhandler {

 @exceptionhandler(value =exception.class)
 public string exceptionhandler(exception e){
 system.out.println("未知异常!原因是:"+e);
 return e.getmessage();
 }
}

上述的示例中,我们对捕获的异常进行简单的二次处理,返回异常的信息,虽然这种能够让我们知道异常的原因,但是在很多的情况下来说,可能还是不够人性化,不符合我们的要求。

那么我们这里可以通过自定义的异常类以及枚举类来实现我们想要的那种数据吧。

自定义基础接口类

首先定义一个基础的接口类,自定义的错误描述枚举类需实现该接口。

代码如下:

public interface baseerrorinfointerface {
 /** 错误码*/
 string getresultcode();
 
 /** 错误描述*/
 string getresultmsg();
}

自定义枚举类

然后我们这里在自定义一个枚举类,并实现该接口。

代码如下:

public enum commonenum implements baseerrorinfointerface {
 // 数据操作错误定义
 success("200", "成功!"), 
 body_not_match("400","请求的数据格式不符!"),
 signature_not_match("401","请求的数字签名不匹配!"),
 not_found("404", "未找到该资源!"), 
 internal_server_error("500", "服务器内部错误!"),
 server_busy("503","服务器正忙,请稍后再试!")
 ;

 /** 错误码 */
 private string resultcode;

 /** 错误描述 */
 private string resultmsg;

 commonenum(string resultcode, string resultmsg) {
 this.resultcode = resultcode;
 this.resultmsg = resultmsg;
 }

 @override
 public string getresultcode() {
 return resultcode;
 }

 @override
 public string getresultmsg() {
 return resultmsg;
 }

}

自定义异常类

然后我们在来自定义一个异常类,用于处理我们发生的业务异常。

代码如下:

public class bizexception extends runtimeexception {

 private static final long serialversionuid = 1l;

 /**
 * 错误码
 */
 protected string errorcode;
 /**
 * 错误信息
 */
 protected string errormsg;

 public bizexception() {
 super();
 }

 public bizexception(baseerrorinfointerface errorinfointerface) {
 super(errorinfointerface.getresultcode());
 this.errorcode = errorinfointerface.getresultcode();
 this.errormsg = errorinfointerface.getresultmsg();
 }
 
 public bizexception(baseerrorinfointerface errorinfointerface, throwable cause) {
 super(errorinfointerface.getresultcode(), cause);
 this.errorcode = errorinfointerface.getresultcode();
 this.errormsg = errorinfointerface.getresultmsg();
 }
 
 public bizexception(string errormsg) {
 super(errormsg);
 this.errormsg = errormsg;
 }
 
 public bizexception(string errorcode, string errormsg) {
 super(errorcode);
 this.errorcode = errorcode;
 this.errormsg = errormsg;
 }

 public bizexception(string errorcode, string errormsg, throwable cause) {
 super(errorcode, cause);
 this.errorcode = errorcode;
 this.errormsg = errormsg;
 }
 

 public string geterrorcode() {
 return errorcode;
 }

 public void seterrorcode(string errorcode) {
 this.errorcode = errorcode;
 }

 public string geterrormsg() {
 return errormsg;
 }

 public void seterrormsg(string errormsg) {
 this.errormsg = errormsg;
 }

 public string getmessage() {
 return errormsg;
 }

 @override
 public throwable fillinstacktrace() {
 return this;
 }

}

自定义数据格式

顺便这里我们定义一下数据的传输格式。

代码如下:

public class resultbody {
 /**
 * 响应代码
 */
 private string code;

 /**
 * 响应消息
 */
 private string message;

 /**
 * 响应结果
 */
 private object result;

 public resultbody() {
 }

 public resultbody(baseerrorinfointerface errorinfo) {
 this.code = errorinfo.getresultcode();
 this.message = errorinfo.getresultmsg();
 }

 public string getcode() {
 return code;
 }

 public void setcode(string code) {
 this.code = code;
 }

 public string getmessage() {
 return message;
 }

 public void setmessage(string message) {
 this.message = message;
 }

 public object getresult() {
 return result;
 }

 public void setresult(object result) {
 this.result = result;
 }

 /**
 * 成功
 * 
 * @return
 */
 public static resultbody success() {
 return success(null);
 }

 /**
 * 成功
 * @param data
 * @return
 */
 public static resultbody success(object data) {
 resultbody rb = new resultbody();
 rb.setcode(commonenum.success.getresultcode());
 rb.setmessage(commonenum.success.getresultmsg());
 rb.setresult(data);
 return rb;
 }

 /**
 * 失败
 */
 public static resultbody error(baseerrorinfointerface errorinfo) {
 resultbody rb = new resultbody();
 rb.setcode(errorinfo.getresultcode());
 rb.setmessage(errorinfo.getresultmsg());
 rb.setresult(null);
 return rb;
 }

 /**
 * 失败
 */
 public static resultbody error(string code, string message) {
 resultbody rb = new resultbody();
 rb.setcode(code);
 rb.setmessage(message);
 rb.setresult(null);
 return rb;
 }

 /**
 * 失败
 */
 public static resultbody error( string message) {
 resultbody rb = new resultbody();
 rb.setcode("-1");
 rb.setmessage(message);
 rb.setresult(null);
 return rb;
 }

 @override
 public string tostring() {
 return jsonobject.tojsonstring(this);
 }

}

自定义全局异常处理类

最后我们在来编写一个自定义全局异常处理的类。

代码如下:

@controlleradvice
public class globalexceptionhandler {
 private static final logger logger = loggerfactory.getlogger(globalexceptionhandler.class);
 
 /**
 * 处理自定义的业务异常
 * @param req
 * @param e
 * @return
 */
 @exceptionhandler(value = bizexception.class) 
 @responsebody 
 public resultbody bizexceptionhandler(httpservletrequest req, bizexception e){
 logger.error("发生业务异常!原因是:{}",e.geterrormsg());
 return resultbody.error(e.geterrorcode(),e.geterrormsg());
 }

 /**
 * 处理空指针的异常
 * @param req
 * @param e
 * @return
 */
 @exceptionhandler(value =nullpointerexception.class)
 @responsebody
 public resultbody exceptionhandler(httpservletrequest req, nullpointerexception e){
 logger.error("发生空指针异常!原因是:",e);
 return resultbody.error(commonenum.body_not_match);
 }


 /**
 * 处理其他异常
 * @param req
 * @param e
 * @return
 */
 @exceptionhandler(value =exception.class)
 @responsebody
 public resultbody exceptionhandler(httpservletrequest req, exception e){
 logger.error("未知异常!原因是:",e);
 return resultbody.error(commonenum.internal_server_error);
 }
}

因为这里我们只是用于做全局异常处理的功能实现以及测试,所以这里我们只需在添加一个实体类和一个控制层类即可。

实体类

又是万能的用户表 (^▽^)

代码如下:

public class user implements serializable{
 private static final long serialversionuid = 1l;
 /** 编号 */
  private int id;
  /** 姓名 */
  private string name;
  /** 年龄 */
  private int age;
  
  public user(){
  }

 public int getid() {
  return id;
 }
 
 public void setid(int id) {
  this.id = id;
 }

 public string getname() {
  return name;
 }

 public void setname(string name) {
  this.name = name;
 }

 public int getage() {
  return age;
 }

 public void setage(int age) {
  this.age = age;
 }

 public string tostring() {
  return jsonobject.tojsonstring(this);
 }
}

controller 控制层

控制层这边也比较简单,使用restful风格实现的crud功能,不同的是这里我故意弄出了一些异常,好让这些异常被捕获到然后处理。这些异常中,有自定义的异常抛出,也有空指针的异常抛出,当然也有不可预知的异常抛出(这里我用类型转换异常代替),那么我们在完成代码编写之后,看看这些异常是否能够被捕获处理成功吧!

代码如下:

@restcontroller
@requestmapping(value = "/api")
public class userrestcontroller {

 @postmapping("/user")
 public boolean insert(@requestbody user user) {
  system.out.println("开始新增...");
  //如果姓名为空就手动抛出一个自定义的异常!
  if(user.getname()==null){
   throw new bizexception("-1","用户姓名不能为空!");
  }
  return true;
 }

 @putmapping("/user")
 public boolean update(@requestbody user user) {
  system.out.println("开始更新...");
  //这里故意造成一个空指针的异常,并且不进行处理
  string str=null;
  str.equals("111");
  return true;
 }

 @deletemapping("/user")
 public boolean delete(@requestbody user user) {
  system.out.println("开始删除...");
  //这里故意造成一个异常,并且不进行处理
  integer.parseint("abc123");
  return true;
 }

 @getmapping("/user")
 public list<user> findbyuser(user user) {
  system.out.println("开始查询...");
  list<user> userlist =new arraylist<>();
  user user2=new user();
  user2.setid(1l);
  user2.setname("xuwujing");
  user2.setage(18);
  userlist.add(user2);
  return userlist;
 }
 
}

app 入口

和普通的springboot项目基本一样。

代码如下:

@springbootapplication
public class app 
{
 public static void main( string[] args )
 {
  springapplication.run(app.class, args);
  system.out.println("程序正在运行...");
 }
}

功能测试

我们成功启动该程序之后,使用postman工具来进行接口测试。

首先进行查询,查看程序正常运行是否ok,使用get 方式进行请求。

get http://www.lhsxpumps.com/_localhost:8181/api/user

返回参数为:

{"id":1,"name":"xuwujing","age":18}

示例图:


可以看到程序正常返回,并没有因自定义的全局异常而影响。

然后我们再来测试下自定义的异常是否能够被正确的捕获并处理。

使用post方式进行请求

post http://www.lhsxpumps.com/_localhost:8181/api/user

body参数为:

{"id":1,"age":18}

返回参数为:

{"code":"-1","message":"用户姓名不能为空!","result":null}

示例图:

可以看出将我们抛出的异常进行数据封装,然后将异常返回出来。

然后我们再来测试下空指针异常是否能够被正确的捕获并处理。在自定义全局异常中,我们除了定义空指针的异常处理,也定义最高级别之一的exception异常,那么这里发生了空指针异常之后,它是回优先使用哪一个呢?这里我们来测试下。

使用put方式进行请求。

put http://www.lhsxpumps.com/_localhost:8181/api/user

body参数为:

{"id":1,"age":18}

返回参数为:

{"code":"400","message":"请求的数据格式不符!","result":null}

示例图:


我们可以看到这里的的确是返回空指针的异常护理,可以得出全局异常处理优先处理子类的异常。

那么我们在来试试未指定其异常的处理,看该异常是否能够被捕获。

使用delete方式进行请求。

delete http://www.lhsxpumps.com/_localhost:8181/api/user

body参数为:

{"id":1}

返回参数为:

{"code":"500","message":"服务器内部错误!","result":null}

这里可以看到它使用了我们在自定义全局异常处理类中的exception异常处理的方法。

到这里,测试就结束了。顺便再说一下,自义定全局异常处理除了可以处理上述的数据格式之外,也可以处理页面的跳转,只需在新增的异常方法的返回处理上填写该跳转的路径并不使用responsebody 注解即可。 细心的同学也许发现了在globalexceptionhandler类中使用的是controlleradvice注解,而非restcontrolleradvice注解,如果是用的restcontrolleradvice注解,它会将数据自动转换成json格式,这种于controller和restcontroller类似,所以我们在使用全局异常处理的之后可以进行灵活的选择处理。

其它

关于springboot优雅的全局异常处理的文章就讲解到这里了,如有不妥,欢迎指正!

项目地址

springboot全局异常的处理项目工程地址:

https://github.com/xuwujing/springboot-study/tree/master/springboot-exceptionhandler

springboot整个集合的地址:

https://github.com/xuwujing/springboot-study

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网