How to handle exception gracefully in a mature java project

Java Sieger 2021-01-21 13:44:20
handle exception gracefully mature java


( One ) summary

Exception handling is the most important part of a system , When a project gets big , Exception handling and logging systems allow you to quickly locate problems . For users or interface callers , Elegant exception handling allows callers to quickly know where the problem is . This article will show you how to handle exceptions gracefully .

( Two ) Using a common return body

We want all the mistakes to be made with Json The way to return to the customer , So take out the general return body that you wrote last time , Create a new class CommonResult Record return body .

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult {
private int code;
private String message;
private Object data;
}
Copy code 

Create a new enumeration class ResponseCode Integrate code and message.

public enum ResponseCode {
// System module
SUCCESS(0, " Successful operation "),
ERROR(1, " operation failed "),
SERVER_ERROR(500, " Server exception "),
// General module 1xxxx
ILLEGAL_ARGUMENT(10000, " Illegal parameter "),
REPETITIVE_OPERATION(10001, " Do not repeat the operation "),
ACCESS_LIMIT(10002, " Too many requests , Please try again later "),
MAIL_SEND_SUCCESS(10003, " Mail sent successfully "),
// User module 2xxxx
NEED_LOGIN(20001, " Login failure "),
USERNAME_OR_PASSWORD_EMPTY(20002, " User name or password cannot be empty "),
USERNAME_OR_PASSWORD_WRONG(20003, " Wrong user name or password "),
USER_NOT_EXISTS(20004, " The user doesn't exist "),
WRONG_PASSWORD(20005, " Wrong password "),
;
ResponseCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
private Integer code;
private String msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Copy code 

( 3、 ... and ) Custom runtime exception

Customize a runtime exception class , The construction method can pass in an exception parameter .

public class MyException extends RuntimeException{
private String msg;
public MyException(String msg) {
super(msg);
}
}
Copy code 

( Four ) Write a unified exception handling class

Exception handling class is the core of exception handling ,SpringBoot Provided in ControllerAdvice Annotations to intercept exceptions , Use RestControllerAdvice Annotations guarantee the return of Json Format .

If the intercepted exception belongs to MyException, Then press Json The format returns the wrong result .

@RestControllerAdvice
public class ExceptionController {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(Exception e){
// If the exception thrown is a custom exception , So JSON Format return
if (e instanceof MyException){
return new CommonResult(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getMsg()," The custom error is :"+e.getMessage());
}
// If not, print out the abnormal information
return new CommonResult(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getMsg()," The error message is :"+e.getMessage());
}
}
Copy code 

( 5、 ... and ) test

To see the initial effect , Here you manually throw an exception to test , newly build IndexController, Throw an exception manually

@RestController
public class IndexController {
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String index(){
throw new MyException(" test ");
}
}
Copy code 

Look at the call results :

 Insert picture description here

( 6、 ... and ) Verification of entity classes

There's a scene like this , The length of user name and password is limited when login , There are format restrictions on mobile phone numbers , If you don't meet the requirements, you can't register . This function can limit , But for back-end interfaces , Restrictions are also needed , In case the front end is not restricted .

Import two validation dependency packages :

<!-- check -->
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
Copy code 

Write entity class , Add the validation parameters of the validation package to each attribute .

@Data
public class Register {
@Length(max = 20,min = 4,message = " The length of the user name needs to be in 4 To 20 Between characters ")
@NotBlank(message = " The username cannot be empty ")
private String username;
@NotBlank(message = " Cell phone number cannot be empty ")
@Pattern(regexp = "^1[3|4|5|8][0-9]d{8}$",message = " The phone number format is incorrect ")
private String phone;
@Length(max = 20,min = 4,message = " The password length needs to be in 4 To 20 Between characters ")
@NotBlank(message = " The password cannot be empty ")
private String password;
}
Copy code 

We add... To the methods we need to use @Valid Annotation for verification , Like this post In the request, I want to check .

@PostMapping("/register")
public CommonResult register(@Valid @RequestBody Register register){
// A series of registered businesses
userService.registerUser(register);
return new CommonResult(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getMsg(),"");
}
Copy code 

@Valid In the case of verification failure, an exception with illegal parameters will be reported , Or catching exceptions in a unified exception handling class , If it is MethodArgumentNotValidException, Take out the corresponding message data .

@RestControllerAdvice
public class ExceptionController {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(Exception e){
// If the parameter verification is abnormal , Just throw a verification error
if (e instanceof MethodArgumentNotValidException){
MethodArgumentNotValidException methodArgumentNotValidException= (MethodArgumentNotValidException) e;
return new CommonResult(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getMsg(),
" Check error :"+methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());
}// If it's a custom exception , Give the specific reason for the exception
else if (e instanceof MyException){
return new CommonResult(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getMsg()," The custom error is :"+e.getMessage());
}
// If not, print out the abnormal information
return new CommonResult(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getMsg()," The error message is :"+e.getMessage());
}
}
Copy code 

( 7、 ... and ) Test verification

Next, you can test the function of verification , adopt postman visit

 Insert picture description here

If the input parameter does not meet the previous setting , Will give specific error messages . Instead of throwing out unacceptable errors :

 Insert picture description here

( 8、 ... and ) summary

The last thing many people think about when they write code is exception handling , Simply implement the requirements , That's why it leads to a lot of unpredictable bug appear .

Reference resources :《2020 newest Java Basic video tutorial and learning route !》
do
link :https://juejin.cn/post/691981...

版权声明
本文为[Java Sieger]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121134316933l.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云