- controller
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.example.demo.exception.MyException;
@RestController
@RequestMapping("/ext")
public class ExceptionController {@RequestMapping("/test1")
public Object test1(){
int a = 1/0;
return a;
}
@RequestMapping("/test2")
public Object test2(){
throw new MyException(500, "服务器繁忙");
}
}
- 自定义异常类MyException
package com.example.demo.exception;
public class MyException extends RuntimeException{
private static final long serialVersionUID = 1L;
private int code;
private String msg;public MyException(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}public int getCode() {
return code;
}public void setCode(int code) {
this.code = code;
}public String getMsg() {
return msg;
}public void setMsg(String msg) {
this.msg = msg;
}
}
- 异常处理类MyExceptionHandler,此处需要注意异常优先级,哪个异常类与抛出的异常关系越紧密优先级越高,处理方式没有硬性要求,此处列举2种方式:返回json、跳转error页面
package com.example.demo.exception;
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;
import org.springframework.web.servlet.ModelAndView;@ControllerAdvice
public class MyExceptionHandler {@ExceptionHandler(value=Exception.class)
@ResponseBody
public Object handlerException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code", 100);
map.put("url", request.getRequestURL());
map.put("msg", e.getMessage());
return map;
}
@ExceptionHandler(value=MyException.class)
public Object handlerException(MyException e, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("code", e.getCode());
modelAndView.addObject("msg", e.getMsg());
modelAndView.setViewName("error");
return modelAndView;
}
}
- error.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<p th:text="'code: '+${code}"></p>
<p th:text="'msg: '+${msg}"></p>
</body>
</html>