1.首先我们先自定义一个异常以及相应属性
package org.xz.test.exception;
//定义自定义异常
public class MyException extends Exception {
private String code;
private String msg;
public MyException() {
super();
}
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;
}
}
package org.xz.test.exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 此项目发生的异常都会进入此类拦截并进行处理
*/
@RestControllerAdvice
public class GolbException {
/**
* 全局异常处理
* 以Json形式返回异常
* @return
*/
@ExceptionHandler(Exception.class)
public Object exec1(Exception e, HttpServletRequest request){
Map map = new HashMap();
map.put("code","404");
map.put("msg",e.getMessage());
map.put("url",request.getRequestURI());
return map;
}
/**
* 自定义异常处理
* 跳转路径 页面返回
* @return
*/
@ExceptionHandler(MyException.class)
public Object exec2(MyException e,HttpServletRequest request){
ModelAndView mv = new ModelAndView();
mv.addObject("code",e.getCode());
mv.addObject("msg",e.getMessage());
mv.setViewName("erro");
return mv;
}
}
自定义异常我们设置一个跳转的html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
页面跳转错误
</body>
</html>
3.新建一个controller来进行测试(我们这里返回一个实体类)
实体类
package org.xz.test.entity;
import org.springframework.stereotype.Component;
@Component
public class UserInfo {
private String name;
private String pwd;
public UserInfo() {
super();
}
public UserInfo(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
controller 控制器
package org.xz.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.xz.test.entity.UserInfo;
import org.xz.test.exception.MyException;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ExceptionController {
//注入装配实体类
@Autowired
private UserInfo userInfo;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
@GetMapping("/exec1")
@ResponseBody
public UserInfo find1(){
int a = 1/0;
return userInfo;
}
@GetMapping("/exec2")
public UserInfo find2() throws MyException {
throw new MyException("404","引发自定义异常");
}
}
现在我们进行测试:
1.先测试全局异常处理
2.测试自定义异常处理