Online Education Project [Unified Exception Handling]

Table of contents

1. Unified exception handling

Why do exceptions need to be handled uniformly? 

1.1: Test the system's response to exceptions

Two ways to handle exceptions globally

The first way: try...catch to handle exceptions    

The second way: configure exception handling class

1.3: Special exception handling configuration

1.4: Custom exceptions

1.4.1: EduException generic exception class

1.4.2: Create a catch custom exception class

1.4.3: Exception tool class


1. Unified exception handling

Why do exceptions need to be handled uniformly? 

When a user is experiencing a product, if there is a problem with the product, an error will be reported, such as: 400, 404, 403, 500, and reporting this exception to the user is too much. Causes a very bad user experience, but it is inevitable that exceptions will occur. Here, unified exception capture and processing are carried out to give user-friendly prompts

1.1: Test the system's response to exceptions

For example: In the teacher service, when we add a lecturer, the time is not added according to the format [yyyy-MM-dd HH:mm:ss],

The demo program reports an error:

Two ways to handle exceptions globally

The first way: try...catch to handle exceptions    

The program error has been demonstrated above, and then we solve it by try catch

This problem occurs when adding a teacher controller in the teacher service. I make an exception to the method of adding a teacher in the controller. Try ...catch

    @ApiOperation("添加老师")
    @PostMapping
    public BaseResult addteacher(@RequestBody EduTeacher eduTeacher){
        boolean flag = false;
        try {
            flag = eduTeacherService.save(eduTeacher);
            throw new RuntimeException("报错了");
        } catch (Exception e) {
          return BaseResult.error("系统错误");
        }
     
    }

The exception is successfully captured here 

But if the exception of each method is used try, the cost is too much and it is very troublesome. We can do global processing in the second way

The second way: configure exception handling class

  • provided by spring mvc@RestControllerAdvice注解

  • @ControllerAdviceIt is an annotation that enhances the Controller. It has three main functions:

    1. Global exception handling (*)

    2. global data binding

    3. global data preprocessing

In the common module: configure exception handling classes in the zx_common_practise module

 Note: For this configuration class to be loaded successfully, the spring boot class must be scanned to

In this way, TeacherApplication can successfully scan into the exception package written 

@RestControllerAdvice  // 对Controller进行增强也就是说进行处理,
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)//拦截什么异常
    public BaseResult error(Exception e){
        e.printStackTrace();
        return BaseResult.error("系统错误");
    }

 Take a look at the effect:

Simulate a division by 0 exception, and simulate a division by 0 exception in the method of querying all teachers

    @GetMapping
    @ApiOperation("查询所有老师")
    public BaseResult findAll(){

        List<EduTeacher> list = eduTeacherService.list();
        //添加一个除0异常
        int exception = 1/0;
        return BaseResult.ok("查询成功",list);
    }

 Swagger test: the system error is successfully captured here

Note: @RestControllerAdvice and @controllerAdvice have the same meaning as @ResponseBody

This is equivalent to adding a try...catch to each method in the controller class 

After the exception is handled in the future development, it will not be visible. Two ways to get exception information

Option 1: Simple processing of the development node, printing the exception to the console

Option 2: Build the environment. Use [log log] to record exceptions

1.3: Special exception handling configuration

What does special exception handling configuration mean? Simply put, it is more precise to handle exceptions

In the following figure, try...catch the exception in the controller method. It is the same exception and the biggest exception as the Exception in the unified configuration exception. We all know that the exception can catch multiple exceptions in the left figure below, and the precision is more careful. Like Exception is the biggest exception, we can capture the exception more accurately!

 Precisely capture and process exceptions in the exception configuration class. The following is a demonstration of the exception except for 0

It can be seen that the exception except 0 is: ArithmeticException, which is specially captured in the exception handling class for precise processing

 

1.4: Custom exceptions

Like the above global unified exception handling and special exception handling can already handle most common problems

Why is there a custom exception? And custom exceptions will still account for most of the future development

For example:

If you write a function to add users, the method is implemented in Serive, and the success or failure of the addition may return a Boolean value true or false, which is normal logic.

Now there is a complicated user to add. Before adding, the boss wants you to determine whether the user name exists or the gender of the password, and perform a wave of verification. After the verification is completed, it may not be true/false, and it may return a string , may return the object, then the exception will play a role, because the exception can carry information, in the Service layer can be checked directly after the throw an exception, we go to the controller layer to grab the exception to get the information, so also The processing of the verification judgment is completed!

If you try in the Controller layer, it is obviously redundant to try each method, so that global exception handling is performed.

1.4.1: EduException generic exception class

 Throwing custom exceptions in Service to exception handling, how should I choose

Custom exception: Exception compile-time exception, RuntimeException runtime exception

Run-time exceptions are still used in most cases, because compile-time exceptions are declared on methods and each caller needs to handle them. Trouble!

Runtime exceptions, when you try, you don’t know whether the exceptions generated by the system itself or the exceptions you customize when you grab them, because many runtime exceptions include a wide range, and it’s hard to distinguish whether it’s your own definition. The Runtime is still the Runtime produced by the system, what should I do?

To solve the problem, we can inherit Runtime exceptions and use its subclasses, and use subclasses to throw our own custom exceptions, which is a good solution.

code example 

Create custom EduException exception class in zx_common_practise

1.4.2: Create a catch custom exception class

  • Test: Throw EduException at the required position in the business, for example an error in the query list:

    @GetMapping
    @ApiOperation("查询所有老师")
    public BaseResult findAll(){
        if (true){
        //    throw new RuntimeException("我就是运行时异常");  
            //    如果按照这种进行抛出压根不知道是自定义的异常抛出还是系统的运行时异常抛出
            throw new EduException("我是自定义异常");
        }
        List<EduTeacher> list = eduTeacherService.list();
        return BaseResult.ok("查询成功",list);
    }
  • Add a custom handler method to the GlobalExceptionHandler class

    @ExceptionHandler(EduException.class)
    public BaseResult error(EduException e){
        e.printStackTrace();
        return BaseResult.error(e.getMessage());
    }

1.4.3: Exception tool class

 

What is this tool for?

Throwing a custom exception in the above requires a new exception: as shown above

We extract the process of this new exception into a tool class, so that we don't need to recreate it every time

Call the method in the tool class directly

 

 Tool class: source code

public class ExceptionUtils {
    /**
     * 抛出异常
     * @param message
     */
    public static void cast(String message) {
        throw new EduException(message);
    }
}

Guess you like

Origin blog.csdn.net/m0_64550837/article/details/126680226