在日常 web 开发中发生了异常,往往需要通过一个统一的 异常处理,来保证客户端能够收到友好的提示。本文将会介绍 Spring Boot 中的 全局统一异常处理。
Springboot的全局异常查是通过两个注解@ControllerAdvice和@ExceptionHandler来实现的。
只有代码出错或者throw出来的异常才会被捕捉处理,如果被catch的异常,就不会被捕捉,除非catch之后再throw异常。
@ControllerAdvice:增强型控制器,对于控制器的全局配置放在同一个位置,全局异常的注解,放在类上。
@ControllerAdvice默认只会处理controller层抛出的异常,如果需要处理service层的异常,需要定义一个自定义的MyException来继承RuntimeException类,然后@ExceptionHandler(MyException)即可。
@ExceptionHandler:指明需要处理的异常类型以及子类。注解放在方法上面。
项目设置
GlobalExceptionHandler.java
package com.dx.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice(basePackages = "com.dx.controller") public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) @ResponseBody public Map<String, Object> errorResult() { Map<String, Object> errorResult = new HashMap<String, Object>(); errorResult.put("errorCode", "500"); errorResult.put("errorMsg", "AOP捕获全局异常。"); return errorResult; } // ⒈全局异常处理返回字符串 @ExceptionHandler(MyPageException.class) @ResponseBody public String exception(MyPageException e) {// 未知的异常做出响应 return "MyPageException"; } // ⒉全局异常处理返回JSON @ExceptionHandler(value = MyJsonException.class) @ResponseBody public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyJsonException e) throws Exception { ErrorInfo<String> r = new ErrorInfo<String>(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("Some Data"); r.setUrl(req.getRequestURL().toString()); return r; } // ⒊全局异常处理返回JSP @ExceptionHandler(MyJspException.class) public String exception(Exception e) { return "MyJspException"; } }
ErrorInfo.java
package com.dx.controller; public class ErrorInfo<T> { public static final Integer OK = 0; public static final Integer ERROR = 100; private Integer code; private String message; private String url; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
MyJsonException.java
package com.dx.controller; public class MyJsonException extends Exception { public MyJsonException(String message) { super(message); } }
MyJspException.java
package com.dx.controller; public class MyJspException extends Exception { public MyJspException(String message) { super(message); } }
MyPageException.java
package com.dx.controller; public class MyPageException extends Exception { public MyPageException(String message) { super(message); } }
App.java
package com.dx; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
测试类:
TestController.java
package com.dx.controller.member; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dx.controller.MyJsonException; import com.dx.controller.MyJspException; import com.dx.controller.MyPageException; @Controller public class TestController { @RequestMapping("/json") public String json() throws MyJsonException { if (1 == 1) throw new MyJsonException(""); return "index"; } @RequestMapping("/jsp") public String jsp() throws MyJspException { if (1 == 1) throw new MyJspException(""); return "index"; } @RequestMapping("/page") public String page() throws MyPageException { if (1 == 1) throw new MyPageException(""); return "index"; } @RequestMapping("/common1") public String common1() throws RuntimeException { if (1 == 1) throw new RuntimeException(""); return "index"; } @RequestMapping("/common2") public String common2() throws Exception { int i = 2 / 0; return "index"; } }
测试1 json:
http://localhost:8080/json
测试2 page:
http://localhost:8080/page
测试3 jsp:
http://localhost:8080/jsp
注:需要配置一下才能支持jsp
①需要在pom添加JSP的支持
<!-- 对JSP的解析支持 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- 对JSTL的支持 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
②需要配置application.properties
在src/main/resources下添加application.properties配置文件,并配置如下内容:
# u9875u9762u9ED8u8BA4u524Du7F00u76EEu5F55 spring.mvc.view.prefix=/WEB-INF/ # u54CDu5E94u9875u9762u9ED8u8BA4u540Eu7F00 spring.mvc.view.suffix=.jsp
③需要添加jsp文件
测试4 common1,common2:
http://localhost:8080/common1
http://localhost:8080/common2