-
创建一个maven项目
-
编辑pom文件, 引入springboot父依赖以及web依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringAdviceController</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
-
编写启动类
package cn.zack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AdviceApplication {
public static void main(String[] args) {
SpringApplication.run(AdviceApplication.class, args);
}
}
-
自定义异常类
package cn.zack.config;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 自定义异常类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyException extends RuntimeException {
private long code;
private String msg;
}
-
自定义全局异常处理器
package cn.zack.config;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* 捕捉全局异常
* 通过@RestControllerAdvice对自定义异常MyException进行包装
*/
@RestControllerAdvice
public class MyExceptionHandler {
// 以json格式返回
@ResponseBody
// 捕获MyException类型的异常
@ExceptionHandler(MyException.class)
// 自定义浏览器返回状态码
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map myExceptionHandler(MyException myException) {
HashMap<Object, Object> map = new HashMap<>();
map.put("code", myException.getCode());
map.put("msg", myException.getMsg());
return map;
}
}
-
编写controller,抛出自定义异常进行测试
package cn.zack.controller;
import cn.zack.config.MyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
@RestController
@RequestMapping(path = "/test")
public class MyController {
@GetMapping(path = "/fun1")
public String fun1(@RequestParam("param1") int param1){
try {
int a = 4 / param1;
return "OK";
} catch (Exception e) {
throw new MyException(500L, e.getMessage());
}
}
@GetMapping(path = "/fun2")
public String fun2(){
try {
ArrayList<String> arrayList = new ArrayList<>();
return arrayList.get(1);
} catch (Exception e) {
throw new MyException(500L, e.getMessage());
}
}
}
-
启动应用
调用fun1方法,传入param1=0,制造一个除零异常,可以得到响应报文:
{"msg":"/ by zero","code":500}
调用fun1方法,传入param1=1,得到正常报文:
OK
调用fun2方法,发生空指针异常,得到响应报文:
{"msg":"Index: 1, Size: 0","code":500}