服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解Spring boot/Spring 统一错误处理方案的使用

详解Spring boot/Spring 统一错误处理方案的使用

2021-05-09 14:26明人不说暗话___我喜欢你 Java教程

这篇文章主要介绍了详解Spring boot/Spring 统一错误处理方案的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

当我们开发spring web应用程序时,对于如 ioexception , classnotfoundexception 之类的检查异常,往往编译器会提示程序员采用 try-catch 进行显式捕获,而对于像 classcastexception , nullpointerexception 这类非检查异常,编译器是不会提示你了,这往往也是能体现程序员代码编写能力的一个方面。

在spring web特别是spring-boot应用中,当一个请求调用成功时,一般情况下会返回 json 格式的对象,就像下面图所示:

 

 
详解Spring boot/Spring 统一错误处理方案的使用 

 

但如果请求抛出了一个 runtimeexception 呢?如果我们不做处理,再次调用时将出现下面的页面:

 

 
详解Spring boot/Spring 统一错误处理方案的使用

 

也就是说当调用出现错误时,spring-boot默认会将请求映射到 /error 路径中去,如果没有相应的路径请求处理器,那么就会返回上面的 whitelabel 错误页面。

1、自定义错误处理页面

当然对运行时异常不做处理是不可能的啦!通常的做法是自定义统一错误页面,然后返回。按照上面的思路,我们实现一个请求路径为 /error 的控制器,控制器返回一个资源路径地址,定义请求映射路径为 /error 的控制器并实现 errorcontroller 接口,代码如下:

myerrorpagecontroller

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.example.demo.controller.handler.errorpage;
 
import org.springframework.boot.web.servlet.error.errorcontroller;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
 
/**
 *
 * the class myerrorpagecontroller.
 *
 * description:自定义错误页面
 *
 * @author: huangjiawei
 * @since: 2018年6月13日
 * @version: $revision$ $date$ $lastchangedby$
 *
 */
@controller
public class myerrorpagecontroller implements errorcontroller {
  
  @requestmapping("/error")
  public string handleerror() {
    return "error.html"; // 该资源位于resources/static目录下
  }
  
  @override
  public string geterrorpath() {
    return null;
  }
}

然后在 reosurces/static 目录下建立 error.html 文件:

?
1
2
3
4
5
6
7
8
9
10
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>insert title here</title>
</head>
<body>
    <h1>这是个错误页面!存放在resources/static目录下,spring-boot发生错误时默认调用</h1>
</body>
</html>

再次请求 http://localhost:7000/demo/getuserinfowithnohandler.json ,如下:

 

 
详解Spring boot/Spring 统一错误处理方案的使用 2、使用 @controlleradvice@responsebody@exceptionhandler 统一处理异常

 

在spring中可以使用上面3个注解进行统一异常处理,默认情况下我们可以针对系统中出现的某种类型的异常定义一个统一的处理器handler,比如说系统抛出了一个 nullpointerexception ,那么我们可以定义一个专门针对 nullpointerexception 的处理器,代码如下:

getuserinfowithnullpointerexception 接口

?
1
2
3
4
5
6
7
8
9
/**
 * 测试空指针错误的处理
 * @return
 * @throws nullpointerexception
 */
@requestmapping(value = "getuserinfowithnullpointerexception.json", method = requestmethod.get)
public student getuserinfowithnullpointerexception() throws nullpointerexception {
    throw new nullpointerexception();
}

nullpointerexceptionhandler.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.example.demo.controller.handler;
 
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsebody;
 
import com.example.demo.pojo.errorreturn;
 
/**
 *
 * the class nullpointerexceptionhandler.
 *
 * description:处理空指针
 *
 * @author: huangjiawei
 * @since: 2018年6月13日
 * @version: $revision$ $date$ $lastchangedby$
 *
 */
@controlleradvice
public class nullpointerexceptionhandler {
  @exceptionhandler(nullpointerexception.class)
  @responsebody
  public errorreturn dealnullpointerexception() {
    e.printstacktrace();
    errorreturn error = new errorreturn();
    error.setreturncode("-1");
    error.setdesc("出现空指针异常啦!");
    return error;
  }
}

浏览器执行: http://localhost:7000/demo/getuserinfowithnullpointerexception.json

 

 
详解Spring boot/Spring 统一错误处理方案的使用

 

同样的道理,如果我们还需要为其他的运行时异常提供统一的处理器,那么也可以像上面一样为每一个异常类型定义一个处理器,比如我们又想为 arithmeticexception 定义处理器,那么我们只需要建立一个类或者方法,然后在方法上的 @exceptionhanler 注解内加上 arithmeticexception.class 指定异常类型即可。

不过你有没有发现,这样为每种异常类型定义一个异常处理类或者方法,因为运行时异常类型特别多,不可能为每种类型都指定一个处理器类或方法,针对这种情况,spring也是可以解决的。如果我们没有为某种特定类型异常,如 arithmeticexception 定义处理器,那么我们可以定义一个 exception 或者 throwable 处理器统一处理。

这样做的好处是,减少了处理器类的数量,同时将异常处理转移到父类上面去,这也是继承的一大优势吧!但是,当你既定义了特定类型的异常,同时又定义了 exception 异常的处理器,那么要小心了,这里不一定有优先级的关系,也就是说不一定会出现只执行父异常处理器的情况,可能是只执行a处理器,而不执行b处理器或者只执行b处理器,不执行a处理器。如 nullpointerexceptionhandler 异常会向 exception 异常传递(但 arithmeticexception 不会向 exception 传递)

现在假设我们既定义上面的 nullpointerexceptionhandler ,又定义了下面的 exceptionthrowablehandler ,那么当发生 nullpointerexception 时,就会默认执行 exceptionthrowablehandler 的方法。

exceptionthrowablehandler.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.example.demo.controller.handler;
 
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsebody;
 
import com.example.demo.pojo.errorreturn;
 
/**
 *
 * the class exceptionthrowablehandler.
 *
 * description:有些异常会向高级别异常传递(但arithmeticexception不会向exception传送)
 *
 * @author: huangjiawei
 * @since: 2018年6月13日
 * @version: $revision$ $date$ $lastchangedby$
 *
 */
@controlleradvice
public class exceptionthrowablehandler {
  
  @exceptionhandler(throwable.class)
  @responsebody
  public errorreturn dealthrowable() {
    errorreturn error = new errorreturn();
    error.setdesc("处理throwable!");
    error.setreturncode("-1");
    return error;
  }
  
  @exceptionhandler(exception.class)
  @responsebody
  public errorreturn dealcommonexception() {
    errorreturn error = new errorreturn();
    error.setreturncode("-1");
    error.setdesc("公共异常处理!");
    return error;
  }
}

浏览器执行 : http://localhost:7000/demo/getuserinfowithnullpointerexception.json

 

 
详解Spring boot/Spring 统一错误处理方案的使用

 

可以发现只执行 exception 的处理器,没有执行空指针的处理器,也就是异常处理往上传送了。下面再来看看抛出 arithmeticexception 的情况:

getuserinfowitharithmeticexception.json

?
1
2
3
4
5
6
7
8
9
/**
 * 测试空指针错误的处理
 * @return
 * @throws nullpointerexception
 */
@requestmapping(value = "getuserinfowitharithmeticexception.json", method = requestmethod.get)
public student getuserinfowitharithmeticexception() throws arithmeticexception {
    throw new arithmeticexception();
}

arithmeticexceptionhandler.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.demo.controller.handler;
 
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsebody;
 
import com.example.demo.pojo.errorreturn;
 
@controlleradvice
public class arithmeticexceptionhandler {
  /**
   * 处理arithmeticexception异常
   * @return
   */
  @responsebody
  @exceptionhandler(arithmeticexception.class)
  public errorreturn dealarithmeticexception() {
    errorreturn errorobject = new errorreturn();
    errorobject.setreturncode("-1");
    errorobject.setdesc("算数处理出现异常!");
    return errorobject;
  }
}

浏览器执行 : http://localhost:7000/demo/getuserinfowitharithmeticexception.json

 

 
详解Spring boot/Spring 统一错误处理方案的使用

 

结果发现异常处理并没有往上层的 exceptionhandler 传送。

总结:对于既定义特定类型的处理器,又定义 exception 等父类型的处理器时要特别小心,并不是所有的异常都会往上级处理,如果我们想只减少处理器类的数量,不想为每种特定类型的处理器添加类或者方法,那么小编建议使用 instanceof 关键字对异常类型进行判断即可。

如下面的代码,我们只建立一个公共的异常处理器,处理 exception 异常,同时使用 instanceof 进行判断。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@exceptionhandler(exception.class)
@responsebody
public errorreturn dealcommonexception(exception e) {
  errorreturn error = new errorreturn();
  // 此处可以采用 instanceof 判断异常类型
  if (e instanceof arithmeticexception) {
    error.setreturncode("-1");
    error.setdesc("算数异常处理!");
    return error;
  }
  system.err.println("exception");
  error.setreturncode("-1");
  error.setdesc("公共异常处理!");
  return error;
}

浏览器执行抛出 arithmeticexception 的接口,如下:

 

 
详解Spring boot/Spring 统一错误处理方案的使用

 

本文代码地址: https://github.com/smallercoder/spring_exceptionhandler

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://juejin.im/post/5b2101716fb9a01e80785be2

延伸 · 阅读

精彩推荐