Spring Boot exception handling

Directory

Spring Boot exception handling

introduce

Interceptors vs Filters

custom exception page

custom exception page

Code combat

need

Code

Create a MyErrorController class to simulate exception errors

complete test

global exception

illustrate

Global Exception – Application Example

Create GlobalExceptionHandler.java

Create the corresponding view address global.html

complete test

custom exception

illustrate

Applications

Create AccessException.java

Modify MyErrorController.java

complete test


Spring Boot exception handling

Introduction

1. By default, Spring Boot provides /error to handle all error mappings
2. For machine clients, it will generate a JSON response with details of the error, HTTP status and exception message. For browser clients, respond with a “whitelabel” error view, rendering the same data in HTML

Interceptor VS Filter

1. The scope of use is different
1) The filter implements the javax.servlet.Filter interface, and this interface is defined in the Servlet specification, that is to say, the use of the filter depends on containers such as Tomcat, and the filter can only be used in web programs

2) Interceptor (Interceptor) It is a Spring component and is managed by the Spring container. It does not depend on Tomcat and other containers and can be used alone. It can be used not only in web programs, but also in programs such as Application

2. The trigger timing of filters and interceptors is also different, see the picture below

1) Filter Filter is pre-processed after the request enters the container, but before entering the servlet, and the end of the request is after the servlet is processed

2) The Interceptor is pre-processed after the request enters the servlet and before entering the Controller, and the request ends after the corresponding view is rendered in the Controller

If you don’t understand, please blog about javaweb filter, springmvc’s interceptor and springmvc’s execution process in my column

3. Description: The filter will not handle request forwarding, but the interceptor will handle request forwarding

4. As for the principle and mechanism of filters and interceptors, it has been explained in detail in the blog. Filters are in JavaWeb, intercepting
The interceptor was mentioned in SpringMVC, but I forgot to include it in my column

Custom exception page

Documentation:
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.develop
ping-web-applications.spring-mvc.error-handling.error-pages

Custom exception page description
1. How to find the location of this document, see the step-by-step guide below
https://docs.spring.io/spring-boot/docs/current/reference/html/index.html

Instructions First, click on the link above to open the document, then follow the steps below step by step, and finally go to the screenshot location

  1. a single page html
  2. 8. web
  3. servlet web application
  4. The “Spring Web MVC Framework”
  5. Error Handling
  6. Custom Error Pages

Custom exception page

Code Combat

need

Customize 404.html 500.html 4xx.html 5xx.html When a corresponding error occurs, display the customized page information

Code implementation

Create 4 pages, these pages can be copied

Create MyErrorController class to simulate exception error

@Controller
public class MyErrorController {

    //Simulate a server internal error 500
    @GetMapping("/err")
    public String err() {
        int i = 10 / 0; // Arithmetic exception
        return "manage";
    }

    //Here we configure the Post method request /err2
    @PostMapping("/err2")
    public String err2() {
        //..
        return "manage";
    }
}

Finish the test

● You need to log in first before testing, otherwise you will be returned to the login page by the interceptor

● For /err2, if you use the get method to request, a 400 error will be generated, and you can see 4xx.html

Because this page has been completed in the previous blog, it is too complicated to show here. This article mainly demonstrates the principle and mechanism of exceptions. If you are interested, you can go to the link

test link

http://localhost:8080/xx
http://localhost:8080/err2

http://localhost:8080/err

Global exception

Help

1. @ControllerAdvice + @ExceptionHandler handles global exceptions
2. The bottom layer is supported by ExceptionHandlerExceptionResolver

Global exception-application instance

Requirements: Demonstrate the use of global exceptions, when ArithmeticException, NullPointerException occurs

Do not use the xxx.html matched by the default exception mechanism, but display the error page specified by the global exception mechanism

Create GlobalExceptionHandler.java

1. Write methods to handle specified exceptions. For example, we handle arithmetic exceptions and null pointer exceptions, and multiple exceptions can be specified

2. The exception to be handled here is specified by the programmer

3. Exception e: Indicates the passed exception object after an exception occurs

4. Model model: We can put our abnormal information into the model and pass it to the display page

5. How to get the method of exception occurrence

6. @Slf4j This annotation is used to display the log for programmers to view

/**
 * @ControllerAdvice: Use it to identify a global exception handler/object
 * will be injected into the spring container
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    //1. Write a method to handle specified exceptions. For example, we handle arithmetic exceptions and null pointer exceptions, and multiple exceptions can be specified
    //2. The exception to be handled here is specified by the programmer
    //3. Exception e: Indicates the exception object passed after the exception occurs
    //4. Model model: We can put our exception information into the model and pass it to the display page
    //5. How to get the method of exception occurrence

    @ExceptionHandler({ArithmeticException. class, NullPointerException. class, AccessException. class})
    public String handleAritException(Exception e, Model model, HandlerMethod handlerMethod) {

        log.info("Exception information={}", e.getMessage());
        //Here, put the exception information that occurred into the model, and you can take it out and display it on the error page
        model.addAttribute("msg", e.getMessage());
        //Which is the method to get the exception
        log.info("The exception method is={}", handlerMethod.getMethod());
        return "/error/global"; //view address
    }
}

Create the corresponding view address global.html

Note that this html page must be in the erro file under static resources, otherwise it will not be recognized

templates is to use Thymeleaf to parse the specified file

As long as static resources are placed in the class path: /static , /public , /resources , /META-INF/resources can be directly accessed – if you don’t know the corresponding file, you can take a look (6 messages) Spring boot WEB development – static Resource access—Rest style request processing–Comments on receiving parameters–Complex parameters–Custom object parameters-Automatic encapsulation–Custom converters–Processing JSON–Content negotiation_Chenjue Blog-CSDN Blog

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Global exception - display page</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<hr/>
<div style="text-align: center">
    <h1>A global exception/error occurred :)</h1><br/>
    Exception/error message: <h1 th:text="${msg}"></h1><br/>
    <a href='#' th:href="@{/}">Back to main page</a>
</div>
<hr/>
<img src="images/logo.png"/>
</body>
</html>

Complete the test

Browser http://localhost:8080/err

Custom Exception

Description

1. If the exceptions provided by Spring Boot cannot meet the development needs, programmers can also customize exceptions.

2. @ResponseStatus + custom exception

3. The bottom layer is ResponseStatusExceptionResolver

The underlying call response.sendError(statusCode, resolvedReason);

4. When a custom exception is thrown, it will still match the x.html display according to the status code..

Application example

Requirements: Customize an exception AccessException, when the user accesses a path that is not authorized to access, the exception is thrown and displayed
Custom exception status code..

Create AccessException.java

/**
 * AccessException : an exception we customized
 * Regarding custom exceptions, friends who have forgotten about our blog in java foundation can go to the column EE
 * value = HttpStatus.FORBIDDEN: Indicates that an AccessException has occurred, and the status code we return through the http protocol is 403
 * The corresponding relationship between this status code and custom exception is determined by the programmer [try to set it reasonably]
 */
@ResponseStatus(value = HttpStatus. FORBIDDEN)
public class AccessException extends RuntimeException {

    //Provide a constructor that can specify information
    public AccessException(String message) {
        super(message);
    }

    //Explicitly define the no-argument constructor

    public AccessException() {
    }
}

Modify MyErrorController.java

 // Write a method to simulate an AccessException
    @GetMapping("/err3")
    public String err3(String name) {
        //If the user is not tom, we think that there is no access-simulation
        if(!"tom".equals(name)) {
            //throw new AccessException();
            throw new AccessException("Old Korean custom AccessException..");
        }
        return "manage";//view address, request forwarding
        //return "redirect:/manage.html";
    }

Complete the test

Browser http://localhost:8080/err3

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Java skill treeHome pageOverview 117913 people are studying systematically