Chapter 5 Web development of Spring Boot IV. exception handling of Spring Boot

Learning objectives:

Exception handling of Spring Boot

In the development of Spring Boot application, whether it is the operation of the underlying database, the operation of the business layer or the operation of the control layer, it will be avoided to encounter all kinds of predictable and unpredictable exceptions that need to be handled. If each process handles exceptions separately, the code coupling of the system is high, the workload is heavy and difficult to unify, and the workload of future maintenance is heavy.

If all types of exception handling can be decoupled from each layer, it not only ensures the single function of the relevant processing process, but also realizes the unified processing and maintenance of exception information. Fortunately, the Spring framework supports such an implementation.

This section will explain the unified exception handling of Spring Boot applications in three ways: custom error page, @ ExceptionHandler annotation and @ ControllerAdvice.

Learning content:

1, Custom error page

Add error. In src/main/resources/templates directory of Spring Boot Web application HTML page. When an error or exception occurs during access, Spring Boot will automatically find the page as the error page. Spring Boot provides the following properties for the error page:

timestamp: Error occurrence time;
status: HTTP Status;
error: Cause of error;
exception: Abnormal class name;
message: Exception message (if this error is caused by an exception);
errors: BindingResult Various errors in the exception (if the error is caused by the exception);
trace: Exception tracking information (if this error is caused by an exception);
path: Requested when the error occurred URL route.

The following is an example to explain how to use the custom error page in the development of Spring Boot application.

1. Create Spring Boot Web application based on Thymeleaf template engine CH5_ three

2. Set up Web application ch5_3 context path

server.servlet.context-path=/ch5_3

3. Create a custom exception class MyException

package com.ch.ch5_3.exception;
public class MyException extends Exception {
	private static final long serialVersionUID = 1L;
	public MyException() {
		super();
	}
	public MyException(String message) {
		super(message);
	}
}

4. Create the controller class TestHandleExceptionController

In this controller class, there are four request processing methods. One is to navigate to index There are three different exception handling codes, which are as follows:

package com.ch.ch5_3.controller;
import java.sql.SQLException;

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

import com.ch.ch5_3.exception.MyException;
@Controller
public class TestHandleExceptionController{
	@RequestMapping("/")
	public String index() {
		return "index";
	}
	@RequestMapping("/db")  
    public void db() throws SQLException { 
        throw new SQLException("Database exception");
    }  
	@RequestMapping("/my")  
    public void my() throws MyException {  
        throw new MyException("Custom exception");
    }
	@RequestMapping("/no")  
    public void no() throws Exception {  
        throw new Exception("Unknown exception");
    } 
	
}

5. Organize script style static files

Static files such as JS scripts, CSS styles and pictures are placed in the src/main/resources/static directory by default, and BootStrap and jQuery are introduced.

6. View page

Thymeleaf template places the view page in src/main/resources/templates directory by default. Therefore, we create a new html page file index. In the src/main/resources/templates directory html and error html.

In index In the HTML page, there are four hyperlink requests. Three requests have corresponding processing in the controller, and the other request is 404 error. The specific code is as follows:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
<!-- Default access src/main/resources/static Lower css folder-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
</head>
<body>
	<div class="panel panel-primary">
		<div class="panel-heading">
			<h3 class="panel-title">Exception handling example</h3>
		</div>
	</div>
	<div class="container">
		<div class="row">
			<div class="col-md-4 col-sm-6">
				<a th:href="@{db}">Handling database exceptions</a><br>
				<a th:href="@{my}">Handle custom exceptions</a><br>
				<a th:href="@{no}">Processing unknown errors</a>
				<hr>
				<a th:href="@{nofound}">404 error</a>
			</div>
		</div>
	</div>
</body>
</html>

In error In the HTML page, use the properties provided by Spring Boot for the error page to display the error message. The specific code is as follows:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>error</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
<!-- Default access src/main/resources/static Lower css folder-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
</head>
<body>
  <div class="panel-l container clearfix">
        <div class="error">
            <p class="title"><span class="code" th:text="${status}"></span>Sorry, we can't find the page you want to view</p>
            <div class="common-hint-word">
                <div th:text="${#dates.format(timestamp,'yyyy-MM-dd HH:mm:ss')}"></div>
                <div th:text="${message}"></div>
                <div th:text="${error}"></div>
            </div>
        </div>
    </div>
</body>
</html>

7. Operation


Click to handle database exceptions: use the public void db() throws SQLException method in the controller, which not only throws SQLException, but also does not handle exceptions. When Spring Boot finds that an exception is thrown and not handled, it will automatically find error in the src/main/resources/templates directory The HTML page displays exception information. The effect is as follows:

2, @ ExceptionHandler annotation

Using the custom error page in section 5.5.1 does not really handle exceptions. In this section, we can use the @ ExceptionHandler annotation to handle exceptions.

If there is a method decorated with @ ExceptionHandler annotation in the Controller, when any method of the Controller throws an exception, the method will handle the exception.

[example 5-9] use the @ ExceptionHandler annotation to handle exceptions.

1. Add a method decorated with @ ExceptionHandler annotation in the controller class

	@ExceptionHandler(value=Exception.class)
	public String handlerException(Exception e) {
		//Database exception
		if (e instanceof SQLException) {
			return "sqlError";
		} else if (e instanceof MyException) {//Custom exception
			return "myError";
		} else {//Unknown exception
			return "noError";
		}
	}

2. Create sqlError, myError and noError pages

The sqlError page code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sql</title>
</head>
<body>
	SQL Abnormal.
</body>
</html>

The code of myError page is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>myError</title>
</head>
<body>
	Custom exception.
</body>
</html>

The code of noError page is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	Unknown exception.
</body>
</html>

3. Operation

3, @ ControllerAdvice annotation

The ControllerAdvice annotation, as its name suggests, is an enhanced Controller. Using this Controller, three functions can be realized: Global exception handling, global data binding and global data preprocessing.

The class annotated with @ ControllerAdvice is the unified exception handling class of all classes in the current Spring Boot application. The method annotated with @ ExceptionHandler in this class is used to handle exceptions uniformly. It is not necessary to define exception handling methods in each Controller one by one, because it is effective for all Controller methods annotated with @ RequestMapping.

[example 5-10] use the @ ControllerAdvice annotation to handle global exceptions.

1. Create a class annotated with @ ControllerAdvice

package com.ch.ch5_3.controller;
import java.sql.SQLException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.ch.ch5_3.exception.MyException;
@ControllerAdvice
public class GlobalExceptionHandlerController {
	@ExceptionHandler(value=Exception.class)
	public String handlerException(Exception e) {
		//Database exception
		if (e instanceof SQLException) {
			return "sqlError";
		} else if (e instanceof MyException) {//Custom exception
			return "myError";
		} else {//Unknown exception
			return "noError";
		}
	}
}

2. Operation

Study time:

Learning output:

1. Technical notes 1 time
2. CSDN technology blog 1

Tags: Java Spring

Posted by Edwin Okli on Tue, 19 Apr 2022 11:18:05 +0930