Spring Boot exception processing

Exception handling is a consistency mechanism to identify and respond to errors. The exception handling mechanism can separate the exception handling code from the normal business logic code, making the wrapper readable and robust. In Spring Boot applications, it is important to be able to catch and respond to client errors in a timely manner. In this section, I’ll show you how to handle exceptions in Spring Boot.

1. Relevant notes

Before we get into the demo, let’s take a look at a few annotations related to exception handling in Spring Boot applications

Note the name instructions
@ControllerAdvice This label is used to handle global exception information
@ExceptionHadler Handle specific exception information and return the relevant response to the client

First, we need to use the ** @controllerAdvice ** annotation to define a global exception handling class with the following syntax:

package com.ramostear.exception.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/ * * *@author : ramostear
 * @date: 2019/3/6 0006 - direction * /
@ControllerAdvice
public class UserExceptionHandler {
	//TODO ...
}

Copy the code

Next, we need to define a custom exception handling class that extends the RuntimeException class:

package com.ramostear.exception.handler;

/ * * *@author : ramostear
 * @date: 0006 - thereof manna 2019/3/6 * /
public class UserNotFoundException extends RuntimeException{
    private static final long serialVersionUID = 5534028121297403043L;
}

Copy the code

Finally, we use the **@ExceptionHandler** annotation to define a method to handle a specific exception message with the following syntax:

@ExceptionHandler(value = UserNotFoundException.class)
    public ResponseEntity<Object> exception(UserNotFoundException ex){
        return new ResponseEntity<>("user not found.", HttpStatus.NOT_FOUND);
    }
Copy the code

After the above work is done, we can handle exception messages in the API in the following way:

@GetMapping("/users/{id}")
    public ResponseEntity<Object> getUser(@PathVariable(name = "id") long id){
        if(! userRepo.containsKey ( id )){throw new UserNotFoundException ();
        }
        return new ResponseEntity<> (userRepo.get (id), HttpStatus.OK);
    }
Copy the code

In the next section, I’ll give a complete example of code that uses the HTTP GET method to request user information and returns a “User Not found” message when there is no corresponding user information in the user repository.

2. Custom exception class information – UserNotFoundException. Java

package com.ramostear.exception.handler;

/ * * *@author : ramostear
 * @date: 0006 - thereof manna 2019/3/6 * /
public class UserNotFoundException extends RuntimeException{
    private static final long serialVersionUID = 5534028121297403043L;
}

Copy the code

Note: This is just a simple extension

2. The exception handling – UserExceptionHandler class. Java

package com.ramostear.exception.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/ * * *@author : ramostear
 * @date: 2019/3/6 0006 - direction * /
@ControllerAdvice
public class UserExceptionHandler {


    @ExceptionHandler(value = UserNotFoundException.class)
    public ResponseEntity<Object> exception(UserNotFoundException ex){
        return new ResponseEntity<>("user not found.", HttpStatus.NOT_FOUND); }}Copy the code

In UserExceptionHandler. Java file, we define a user does not exist exception handling method,

3. API classes – UserServiceController. Java

package com.ramostear.exception.handler.controller;

import com.ramostear.exception.handler.UserNotFoundException;
import com.ramostear.exception.handler.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/ * * *@author : ramostear
 * @date7 all: 2019/3/6 0006 - * /
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepo = new HashMap<>();

    @PostConstruct
    public void initUserRepo(a){
        User admin = new User ().setId ( 1 ).setName ( "admin" );
        userRepo.put ( admin.getId (),admin );

        User editor = new User ().setId ( 2 ).setName ( "editor" );
        userRepo.put ( editor.getId (),editor );
    }


    @GetMapping("/users/{id}")
    public ResponseEntity<Object> getUser(@PathVariable(name = "id") long id){
        if(! userRepo.containsKey ( id )){throw new UserNotFoundException ();
        }
        return newResponseEntity<> (userRepo.get (id), HttpStatus.OK); }}Copy the code

In the getUser() method, if the user does not find it, a UserNotFoundException is thrown.

4. The main class of application – ExceptionHandlerApplication. Java

package com.ramostear.exception.handler;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionHandlerApplication {

	public static void main(String[] args) { SpringApplication.run(ExceptionHandlerApplication.class, args); }}Copy the code

5. The User POJO class — user.java

package com.ramostear.exception.handler.model;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/ * * *@author : ramostear
 * @date: 0006 - good tidings 2019/3/6 * /
@Getter
@Setter
@NoArgsConstructor
public class User {

    private long id;

    private String name;

    public User setId(long id){
        this.id = id;
        return this;
    }

    public User setName(String name){
        this.name = name;
        return this; }}Copy the code

6. Maven build file – pom.xml

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3. RELEASE</version>
		<relativePath/> <! -- lookup parent from repository -->
	</parent>
	<groupId>com.ramostear</groupId>
	<artifactId>exception-handler</artifactId>
	<version>0.0.1 - the SNAPSHOT</version>
	<name>exception-handler</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Copy the code

8. Run the tests

Next, we will package and run our application. This tutorial will demonstrate how to run the application using IDEA, as shown below:

Then, start the Postman application, we first enter in the address bar: http://localhost:8080/users/1, observed under normal circumstances the test information:

Postman’s test results show that the request status is 200 and the user details are returned. Now, we update the URL is: http://localhost:8080/users/3, look again test results:

In this case, the HTTP Status is 404 and user not found is displayed.

Gracefully handle Spring Boot exception messages