それならば、今日は統一され、治療のSpringBootグローバルな例外を導入する方法です。グローバルSpringBoot例外処理注釈は、2つの主要な効果がある@ControllerAdviceと@ExceptionHandler、コンポーネントは@ControllerAdvice注釈であり、注釈は要求を傍受することが可能なコントローラクラスを追加すること、およびグローバルexceptionHandlerの注釈が例外処理制御に設けられていてもよいですプロセスの例外をインターセプトすると入力します。例えば:@ExceptionHandler(値= NullPointException.class)。
準備
- SpringBoot 2.1.3
- 考え
- JDK 8
コンフィギュレーションに依存
<dependencies>
<!-- JPA 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql 连接类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok 依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 单元测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
プロファイル
spring:
# 数据库相关
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update #ddl-auto:设为 create 表示每次都重新建表
show-sql: true
リターンメッセージクラス
public class Message<T> implements Serializable {
/**
* 状态码
*/
private Integer code;
/**
* 返回信息
*/
private String message;
/**
* 返回的数据类
*/
private T data;
/**
* 时间
*/
private Long time;
// getter、setter 以及 构造方法略。。。
}
ツール
データと返されたコードを処理するための情報は、非常に詳細なコメントを言っているわけではありません。
public class MessageUtil {
/**
* 成功并返回数据实体类
* @param o
* @param <E>
* @return
*/
public static <E>Message<E> ok(E o){
return new Message<>(200, "success", o, new Date().getTime());
}
/**
* 成功,但无数据实体类返回
* @return
*/
public static <E>Message<E> ok(){
return new Message<>(200, "success", null, new Date().getTime());
}
/**
* 失败,有自定义异常返回
* @param code
* @param msg
* @return
*/
public static <E>Message<E> error(Integer code,String msg){
return new Message<>(code, msg, null, new Date().getTime());
}
}
カスタム例外
RuntimeExceptionを継承することで、宣言コードは、カスタム例外の種類を定義するために使用されます。主に異常なコード取得し、返されたメッセージタイプコードに提供を傍受するために使用されます。
public class CustomException extends RuntimeException{
/**
* 状态码
*/
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public CustomException(Integer code, String message){
super(message);
this.code = code;
}
}
異常な傍受クラス
クラス@RestControllerAdviceコントローラに文を追加することにより@ExceptionHandler例外クラスを追加しながら、ハンドルを要求をインターセプトし、注釈に傍受する方法を指定することもできます。
@RestControllerAdvice // 控制器增强处理(返回 JSON 格式数据),添加了这个注解的类能被 classpath 扫描自动发现
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class) // 捕获 Controller 中抛出的指定类型的异常,也可以指定其他异常
public <E>Message<E> handler(Exception exception){
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else {
return MessageUtil.error(120, "异常信息:" + exception.getMessage());
}
}
}
ここでは、自己の異常や、未知の例外処理の定義のみ、あなたは明確な方法で知っている場合に例外をスローすることがあり、あなたは、特定のプロセスを追加することもできます。たとえば、あなたは明らかに方法がNullPointExceptionが追加NullPointExceptionを扱うことができる投げることを知っています:
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else if (exception instanceof NullPointException ){
return MessageUtil.error(500, "空指针异常信!");
} else {
return MessageUtil.error(120, "异常信息:" + exception.getMessage());
}
コントローラ層
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/{id}")
public Message<Student> findStudentById(@PathVariable("id") Integer id){
if (id < 0){
//测试自定义错误
throw new CustomException(110, "参数不能是负数!");
} else if (id == 0){
//硬编码,为了测试
Integer i = 1/id;
return null;
} else {
Student student = studentService.findStudentById(id);
return MessageUtil.ok(student);
}
}
}
完全なコード
https://github.com/turoDog/Demo/tree/master/springboot_exception_demo
あなたが助けを持っていると考えられる場合は、どうもありがとうございました、私の詠唱スターウォークを与えます。
ポストマンテスト
ログインにhttp:// localhost:8080 /学生/ 5、テストデータの結果が正常に戻りました。
http:// localhost:8080にアクセス/学生/ 0未知の異常なテスト結果。
訪問は、http:// localhostを:異常8080 /学生/ -11カスタムテスト結果。
遂に
あなたがここに表示された場合、あなたはこの記事を気に入って、前方に、親指ください。マイクロチャンネルサーチ「良いバスケットケース」、懸念は「返信した後、1024年には、」あなたのJavaチュートリアルの完全なセットを提供します。