SpringBoot一共有五种异常处理的方式
方式一:@ControllerAdvice+@ExceptionHandler 注解处理异常
GlobalExceptionHandler.java
package com.zk.myspringboot002; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; //全局捕获异常 @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody public Map<String,Object> resultError(){ Map<String,Object> result=new HashMap<String,Object>(); result.put("errorCode", "500"); result.put("errorMsg", "系统错误"); return result; } }
SpringBootApplicationTwice.java
package com.zk.myspringboot002; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; @EnableAutoConfiguration @SpringBootApplication public class SpringBootApplicationTwice { public static void main(String[]args){ SpringApplication.run(SpringBootApplicationTwice.class, args); } public static void run(String...arg0) { System.out.println("Hello world from Command Line Runner"); } }
TestController.java
package com.zk.myspringboot002; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //标识该接口全部返回json格式 @RestController public class TestController { @RequestMapping("/success") public String success() { return "success"; } @RequestMapping("/getMap") public Map<String,Object> index() { Map<String,Object> result=new HashMap<String,Object>(); result.put("errorCode", "200"); result.put("errorMsg", "message"); return result; } @RequestMapping("/fail") public String error() { int i=1/0; return "error"; } }
pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>myspringboot002</groupId> <artifactId>myspringboot002</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> </dependencies> </project>
运行结果如下: