[Note] [https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm](https://www.tutorialspoint.com/spring_bo ot/spring_boot_exception_handling.htm)
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/000cbc701e3742a692a588ad226dbcd7~tplv-k3u1fbpfcp-zoom-1.image)
Handling exceptions and errors in an API is critical for enterprise applications. This article will show you how to handle exceptions in Spring Boot.
Before we look at exception handling, let’s understand the following annotation:

Controller Advice

The @controllerAdvice annotation is used to handle global exceptions.

Exception Handler

The @ExceptionHandler annotation is used to handle the specified exception and send a custom response to the client.
You can use the following code to create the @ControllerAdvice class to handle global exceptions:
package com.tutorialspoint.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice public class ProductExceptionController {}Copy the code

Define a class that inherits RuntimeException.
package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; }Copy the code

The @ExceptionHandler method can be defined to handle exceptions, as shown below. This method should be used to write the Controller Advice class file.
@ExceptionHandler(value = ProductNotfoundException.class)public ResponseEntity<Object> exception(ProductNotfoundException exception) {}
Copy the code

Now use the following code to throw an exception from the API:
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)public ResponseEntity<Object> updateProduct() { throw new ProductNotfoundException(); }Copy the code

The complete exception handling code is shown below. In this example, we use the PUT API to update the product. When updating a Product, if the Product is not found, the response message returned is “Product Not found.” Note that the ProductNotFoundExceptio**n exception class should inherit from RuntimeException**.
package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; }Copy the code

The Controller Advice class handles global exceptions, as shown below. We can define any Exception Handler method in this class file.
package com.tutorialspoint.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvicepublic class ProductExceptionController { @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND); }}Copy the code

The following Product Service API Controller file updates the Product. If the product does not exist, throw the ProductNotFoundException class.
package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.exception.ProductNotfoundException; import com.tutorialspoint.demo.model.Product; @RestControllerpublic class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { if(! productRepo.containsKey(id))throw new ProductNotfoundException(); productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK); }}Copy the code

** The main Spring Boot application class ** files are as follows:
package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code

** Product POJO class ** is as follows:
package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}Copy the code

Maven build — 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" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Tutorialspoint < / groupId > < artifactId > demo < / artifactId > <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name> Demo </name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 1.5.8. RELEASE < / version > < relativePath / > < / parent > <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < 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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code

Gradle Build — Build. Gradle code looks like this:
Buildscript {ext {springBootVersion = '1.5.8.release'} repositories {mavenCentral()} dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'org.springFramework. boot'group = 'com.tutorialspoint'version = '0.0.1-SNAPSHOT'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test')}Copy the code

You can build the JAR using Maven or Gradle commands and run the Spring Boot application:
The Maven command is as follows:
mvn clean install
Copy the code

After “BUILD SUCCESS”, you can find the JAR file in the target directory.
Gradle can use the following command:
gradle clean build
Copy the code

After “BUILD SUCCESSFUL”, you can find the JAR files in the BUILD /libs directory.
You can run the JAR file using the following command.
Java - jar < JARFILE >Copy the code

Start the application on Tomcat port 8080 as follows:
! [](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4368957acb164c33bcf529761baee5d8~tplv-k3u1fbpfcp-zoom-1.image)
Now click on the following URL in the POSTMAN app and you can see the following output:
Update URL: [http://localhost:8080/products/3] (http://localhost:8080/products/3)
! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e5fe89758b0841f584bcd1bf6da7f5de~tplv-k3u1fbpfcp-zoom-1.image)