springboot全局异常处理实例——@ControllerAdvice+ExceptionHandler
文章目录
一、全局捕获异常后,返回json给浏览器
项目结构:
1、自定义异常类 MyException.java
package com.gui.restful;
/**
* 自定义异常类
*/
public class MyException extends RuntimeException{
private String code;
private String msg;
public MyException(String code,String msg){
this.code=code;
this.msg=msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2、控制器 MyController.java
package com.gui.restful;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* controller抛出异常
*/
@RestController
public class MyController {
@RequestMapping("hello")
public String hello() throws Exception{
throw new MyException("101","系统异常");
}
}
3、全局异常处理类 MyControllerAdvice
package com.gui.restful;
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;
import java.util.HashMap;
import java.util.Map;
/**
* 全局异常捕获处理
*/
@ControllerAdvice //controller增强器
public class MyControllerAdvice {
@ResponseBody
@ExceptionHandler(value=MyException.class) //处理的异常类型
public Map myExceptionHandler(MyException e){
Map<String,String> map=new HashMap<>();
map.put("code",e.getCode());
map.put("msg",e.getMsg());
return map;
}
}
4、运行结果
启动应用,访问 http://localhost:8080/hello,出现以下结果,说明自定义异常被成功拦截
二、全局捕获异常后,返回页面给浏览器
1、自定义异常类 MyException.java(同上)
2、控制器 MyController.java(同上)
3、全局异常处理类 MyControllerAdvice
package com.gui.restful;
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;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
/**
* 全局异常捕获处理
*/
@ControllerAdvice //controller增强器
public class MyControllerAdvice {
@ExceptionHandler(value=MyException.class) //处理的异常类型
public ModelAndView myExceptionHandler(MyException e){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("error");
modelAndView.addObject("code",e.getCode());
modelAndView.addObject("msg",e.getMsg());
return modelAndView;
}
}
4、页面渲染 error.ftl(用freemarker渲染)
pom.xml中引入freemarker依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
error.ftl
<!DOCTYPE>
<html>
<head>
<title>错误页面</title>
</head>
<body>
<h1>code:${code}</h1>
<h1>msg:${msg}</h1>
</body>
</html>