@ControllerAdvice + @ExceptionHandler defines global exceptions

  1. Create Spring Boot project: Use Spring Initializr to create a new Spring Boot project.
  2. Dependency configuration: In the pom.xml file (the thymeleaf template engine is used for convenience): a>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
  1. HTML directory structure: Create an HTML view in the src/main/resources/templates directory. Two example views are provided here, error-page.html and result-page.html:

error-page.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>错误页面</title>
</head>
<body>
<h1>错误</h1>
<p th:text="${message}"></p>
</body>
</html>

result-page.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>结果页面</title>
</head>
<body>
<h1>结果</h1>
<p th:text="'结果是:' + ${result}"></p>
</body>
</html>
  1. Define custom exception class: Create a custom exception class, for example MyCustomException:
public class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}
  1. Exception handler class: Create an exception handler classMyCustomExceptionHandler and configure multiple @ExceptionHandler methods to Handle different types of exceptions:
import com.lfsun.demolfsunstudythymeleafcustomexception.exception.MyCustomException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyCustomExceptionHandler {

    @ExceptionHandler(MyCustomException.class)
    public ModelAndView handleCustomException(MyCustomException ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "自定义异常发生了: " + ex.getMessage());
        modelAndView.setViewName("error-page");
        return modelAndView;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllOtherExceptions(Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "发生了其他异常: " + ex.getMessage());
        modelAndView.setViewName("error-page");
        return modelAndView;
    }
}
  1. Controller class: Create a controller class, such as DemoController, and throw a custom exception in it:
import com.lfsun.demolfsunstudythymeleafcustomexception.exception.MyCustomException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DemoController {

    @GetMapping("/divide")
    public String divide(@RequestParam int dividend, @RequestParam int divisor, Model model) throws MyCustomException {
        if (divisor == 0) {
            throw new MyCustomException("不允许除以零。");
        }
        int result = dividend / divisor;
        model.addAttribute("result", result);
        return "result-page";
    }
}
  1. Run project: Run the Spring Boot application.
  2. Access the application: Access http://localhost:8080/divide?dividend=10&divisor=2 this URL in the browser, and the < in DemoController will be executed. /span> to see the custom exception handler in effect. . Try visiting divide method and display the result5http://localhost:8080/divide?dividend=10&divisor=0
    Insert image description here

Guess you like

Origin blog.csdn.net/qq_43116031/article/details/134296957