Exception handling in 11 springboot project

Time:2020-11-21

Background analysis

In the development of the project, whether it is the operation process of the underlying data logic, or the processing process of the business logic, or the processing process of the control logic, all kinds of predictable and unpredictable exceptions will inevitably be encountered. Handling the exception has a good protection effect on the system, and will greatly improve the user experience.

Exception handling analysis

summary

There are two ways to deal with exceptions in Java projects. One is to execute the trycatch operation or to perform the throw operation (throw it to other objects). No matter which way is adopted, the purpose is to let our system have feedback on the exception. But now the problem is how to make the feedback code simple, intuitive and friendly.

Treatment specification

In the process of handling exceptions, we usually have to follow certain design specifications, such as:

  • When catching an exception, it must exactly match the exception thrown, or the catch exception is the parent type of the thrown exception.
  • Avoid throwing runtimeException directly, let alone exception or throwable. Use custom exception with business meaning (such as serviceexception).
  • After an exception is caught, it must be handled (for example, logging). If you don’t want to handle it, you need to throw the exception to its caller.
  • The outermost logic must handle exceptions and translate them into something that the user can understand.
  • Don’t repeat yourself, the day principle.

Exception handling in springboot project

preparation

Step 1: create a project or module and add a web dependency. The code is as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 2: modify the project access port to 80, for example

server.port=80

Step 3: define the controller class. The code is as follows:

package com.cy.pj.arithmetic.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ArithmeticController {

  @RequestMapping("doCompute/{n1}/{n2}")
  @ResponseBody
  public String doCompute(@PathVariable  Integer n1, 
  @PathVariable Integer n2){
          Integer result=n1/n2;
          return "Result is "+result;
  }
}

Step 4 start the project for access testing

Enter in the browser address barhttp://localhost/doCompute/10/2To detect the output results.

Result is 5

Default exception handling

Enter in the browser address barhttp://localhost/doCompute/10/0To detect the output results.

Exception handling in 11 springboot project

For such default exception handling (provided by spring boot), the user experience is not very friendly. In order to present more friendly exception information, we usually need to customize the exception handling.

Self try exception handling

In the control layer method, we can perform try catch processing, for example:

 @RequestMapping("doCompute/{n1}/{n2}")
  @ResponseBody
  public String doCompute(@PathVariable  Integer n1, 
  @PathVariable Integer n2){
          try{
          Integer result=n1/n2;
          return "Result is "+result;
          }catch(ArithmeticException e){
          return "exception is "+e.getMessage();
          }
  } 

There are usually multiple methods in a controller class. If you write a try statement in many methods for exception handling, it will lead to a lot of repetitive code writing, which is not easy to maintain.

Exception handling method defined in controller

Add an exception handling method to the controller class. The code is as follows:

@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public String doHandleArithmeticException(ArithmeticException e){
    e.printStackTrace();
    Return "an exception occurred in the calculation process. The exception information is" + e.getmessage();
}

@The method described in the exceptionhandler annotation is exception handling method (the exception type in the annotation is the exception type that can be handled). If there is an exception in the logic method of the controller class and no exception is handled, it will find whether there is any exception handling method defined in the controller class. If the exception handling method is defined and can handle the thrown exception type, the exception handling method will handle the exception 。

Global exception handling class and method definition in control layer

When a project is defined by several common exception handling methods in multiple control layer classes, we can extract these methods into the common parent class object, but this method is a strong coupling implementation, which is not conducive to code maintenance. We can also implement it with the help of the global exception handling specification defined by the web module in the spring framework, such as defining the global exception handling class. The code is as follows:

package com.cy.pj.common.web;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public String doHandleArithmeticException(ArithmeticException e){
        e.printStackTrace();
        Return "an exception occurred in the calculation process. The exception information is" + e.getmessage();
    }
}

The class described in the @ restcontrolleradvice annotation is a global exception handling class. When the exception in the control layer method is not captured by itself or its internal exception handling method is not defined, the bottom level will find the global exception handling class by default, and call the corresponding exception handling method for exception handling.

Summary

This section mainly analyzes and explains the exception handling mechanism in springboot. The purpose of this paper is to master the exception handling methods in springboot project, and to deal with exceptions in response to different business. So as to effectively improve the user experience and enhance the fault tolerance of the system.