7.12 Business exceptions in Springboot actual combat projects: custom assertion Assert

CSDN achieves 100 million technicians


foreword

I shared the practical experience of global exception handling above, which I mentioned 业务异常, but the exception has not been thrown in the project.

This article will take you to throw this exception in actual combat projects. Actual combat scenarios are often encountered in development: illegal calls, business verification, data errors, or business logic errors, etc. Here, high scalability needs to be considered in terms of architecture and easy maintainability , direct throwing will be very scattered, if it needs to be modified, it will modify a lot of points, so we can uniformly package the throwing business exception into a class, and uniformly control the throwing conditions, throwing The types of business exceptions and exception codes, etc., are the protagonist of this article: custom assertion Assert !

Above address: 7.11 SpringBoot Actual Global Exception Handling- In-depth Details


1. What is an assert assertion

断言It is a term in the programming world. It is assert in English. It probably means that the developer has buried some assumptions in the specified position in advance . If the condition is not true, the program will stop and an exception will occur . The purpose of execution can only continue after the conditions preset by the developer are met !

That is to say, the assertion will clearly put forward strict requirements for the code execution logic, so it is a very effective means to improve the code quality . The more experienced the developer, the more reasonable the use of assertion will be. Therefore, this assertion is really good. use it~


2. Why do you want to customize the assertion Assert?

Java has the assert keyword, which is the realization of the assertion. The specific usage is very simple. In addition, Spring also has the Assert assertion tool class, which will not be discussed here.

为什么不用这些Assert类呢?

The two main points are: cost and flexibility !

  • The cost means that the implementation of the Assert class has no barriers, and the internal implementation is basically the same if (条件) {抛出异常}, so we are fully capable of customizing the Assert tool class!

  • More importantly, it is very flexible, we assemble our own business exceptions and various technical implementation exceptions, unified control, free expansion, no matter how complicated the scene is, we can hold it!

Therefore, let's define a few common assertion scenarios first, and add others when there are scenarios!


3. Empty notNull or ifNull

Next, define the Assert tool class in common:
insert image description here

Bear the brunt of the realization is: judgment empty ! It is the most commonly used assertion. Basically, various scenarios need to be judged as empty, and combined with global exception handling, it can handle various exception logic very coolly!

There are many empty situations. If it is common, for example, at least the following empty spaces must be included:

  • String is null, empty string, space

  • Array/List/Map/Set is null, size() is 0

  • etc.

So, my implementation code is as follows:

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
 * 是否是null 或者 空白
**/
private static boolean isNullOrBlank(Object obj) {
    
    
    if (ObjectUtils.isEmpty(obj)) {
    
    
        return true;
    }
    if (obj instanceof String && !StringUtils.hasText((String)obj)) {
    
    
        return true;
    }
    return false;
}

I believe there is no need to explain too much, I know that everyone’s foundation is very good, and then simply verify (of course you can add more object verification):

public static void main(String[] args) {
    
    
    // 测试isNullOrBlank是否符合期望
    // 空
    System.out.println("null:" + Assert.isNullOrBlank(null));
    System.out.println("空串:" + Assert.isNullOrBlank(""));
    System.out.println("空格:" + Assert.isNullOrBlank(" "));
    Assert anAssert = null;
    System.out.println("空对象:" + Assert.isNullOrBlank(anAssert));
    System.out.println("空数组:" + Assert.isNullOrBlank(new byte[]{
    
    }));
    System.out.println("空List:" + Assert.isNullOrBlank(new ArrayList()));
    System.out.println("空Map:" + Assert.isNullOrBlank(new HashMap()));
    System.out.println("空Set:" + Assert.isNullOrBlank(new HashSet()));
    // 非空
    System.out.println("非空String:" + Assert.isNullOrBlank("g"));
    anAssert = new Assert();
    System.out.println("非空对象:" + Assert.isNullOrBlank(anAssert));
    System.out.println("非空数组:" + Assert.isNullOrBlank(Arrays.asList("").toArray()));
    System.out.println("非空List:" + Assert.isNullOrBlank(Arrays.asList("")));
    Map<String, String> map = new HashMap<>();
    map.put("a", "b");
    System.out.println("非空Map:" + Assert.isNullOrBlank(map));
    System.out.println("非空Set:" + Assert.isNullOrBlank(map.entrySet()));
}

insert image description here

All true and false, exactly as expected! Perfect~

Our first assertion method follows, show you my code~

/**
 * obj不能为空,如果是空则抛出异常
 **/
public static void notNull(Object obj, String msg) {
    
    
    if (isNullOrBlank(obj)) {
    
    
        throw new BizException(msg);
    }
}

Of course, there is another naming method, that is, the method name starts with if, and corresponds to the method if条件. You can freely name it according to your preferences, as follows:

/**
 * obj如果是空则抛出异常
 **/
public static void ifNull(Object obj, String msg) {
    
    
    if (isNullOrBlank(obj)) {
    
    
        throw new BizException(msg);
    }
}

Which do you prefer? Vote for you at the end of the article~


Fourth, judge true isTrue or ifFalse

Learned to judge empty, true judgment is as natural as an apple falling from a tree to the ground:

/**
 * 表达式必须为true,如果不是true则抛出异常
 **/
public static void isTrue(boolean expression, String message) {
    
    
    if (!expression) {
    
    
        throw new BizException(message);
    }
}

Similarly, another naming method:

/**
  * 表达式如果不是true则抛出异常
  **/
public static void ifFalse(boolean expression, String message) {
    
    
    if (!expression) {
    
    
        throw new BizException(message);
    }
}

5. Judgment of false isFalse or ifTrue

At this point, it seems superfluous for me to say one more word! Go directly to the code~!

/**
 * 表达式必须为false,如果是true则抛出异常
 **/
public static void isFalse(boolean expression, String message) {
    
    
    if (expression) {
    
    
        throw new BizException(message);
    }
}

/**
 * 表达式如果是true则抛出异常
 **/
public static void ifTrue(boolean expression, String message) {
    
    
    if (expression) {
    
    
        throw new BizException(message);
    }
}

6. Application assertion Assert

Can Assert be used directly?
certainly!
In the previous actual combat, the service layer directly used it TgResultas the return value, which is where we can use Assert.

Application 1: BookService.saveBook

For example, for the saveBook method of BookService, we can now directly change the return value TgResult<Integer>from Integer:
insert image description here

You should understand the specific modified code at a glance!
insert image description here

insert image description here

应用2: BookBorrowService.examineBookBorrow

I won’t explain much here, the return value can be changed directly void, and the alternative code for the specific judgment is as follows, isn’t it more concise?
insert image description here
insert image description here


at last

== Seeing this, if you find it helpful, brush up on 666, thank you for your support~ ==

If you want to read more practical articles, I still recommend my practical column –> "Based on SpringBoot+SpringCloud+Vue Separation of Front-end and Back-end Projects", a column jointly created by me and the front-end dog brother, which allows you to learn from From 0 to 1, you can quickly have practical experience in enterprise-level standardized projects!

Specific advantages, planning, and technology selection can all be read in " The Beginning "!

After subscribing to the column, you can add my WeChat, and I will provide targeted guidance for each user!

In addition, don't forget to follow me: Tiangang gg , I'm afraid you won't find me, it's not easy to miss new posts: https://blog.csdn.net/scm_2008

Guess you like

Origin blog.csdn.net/scm_2008/article/details/132656559