SpringBoot2.X之旅,@ExceptionHandler、@ControllerAdvice异常统一处理(Web Project)
一、idea新建web项目
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.cobra</groupId>
<artifactId>exceptiondemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>exceptiondemo</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
目录结构:
二、coding:
1、在DemoController,写一个异常:
package com.cobra.exceptiondemo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/4/16 10:25
*/
@RestController
@Slf4j
public class DemoController {
@GetMapping("/demo")
public String demo() {
int[] arrays = {1, 23, 6, 7};
for (int i = 0; i <= arrays.length ; i++) {
log.info("int[{}]={}",i,arrays[i]);
}
return "this is an demo test";
}
}
2、在DemoExceptionHandler,捕获异常,返回自定义的信息:
package com.cobra.exceptiondemo.handler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/4/16 10:26
*/
@ControllerAdvice
@Slf4j
public class DemoExceptionHandler {
@ExceptionHandler(ArrayIndexOutOfBoundsException.class)
@ResponseBody
public String handlerArrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException e) {
log.error(e.getMessage());
e.printStackTrace();
return "数组下标越界";
}
}