参考: https://www.cnblogs.com/lenve/p/10748453.html
@ControllerAdvice或@RestControllerAdvice作用:
1.全局异常处理
2.全局数据绑定
3.全局数据预处理
异常定义:
/**
* 这些状态可以参照 HttpStatus
*/
public enum ResponseStateEnum {
SUCCESS(200),
PARAM_ERROR(400),
TOKEN_INVALID(401),
EXISTED(402),
AUTH_ERROR(403),
NOT_EXIST(404),
SERVER_ERROR(500),
EXPIRED(501);
private final int state;
private ResponseStateEnum(int state) {
this.state = state;
}
public int getState() {
return state;
}
}
/**
* @author gosling
* @description 用于controller层抛出异常, 该异常会被拦截器自动封装成ResponseMessage对象
* @update 修订描述
*/
public class RestMessageException extends RuntimeException {
private ResponseStateEnum responseStateEnum;
public RestMessageException(ResponseStateEnum responseStateEnum, String message) {
super(message);
this.responseStateEnum = responseStateEnum;
}
public int getState() {
return this.responseStateEnum.getState();
}
}
配置示例:
package top.xinzhang0618.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.xinzhang0618.demo.exception.RestMessageException;
/**
* Controller
*
* @author gavin
* @version 2020/6/10 0010
* 使用 RestControllerAdvice 相比 ControllerAdvice 可以省去 @ResponseBody注解
*/
@RestControllerAdvice
public class Controller {
/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "Gavin-test");
}
/**
* 全局异常捕捉处理
*/
@ExceptionHandler(value = RestMessageException.class)
public Map errorHandler(RestMessageException ex) {
Map map = new HashMap(3);
map.put("code", ex.getState());
map.put("msg", ex.getMessage());
return map;
}
}
测试:
@RequestMapping("/test")
@CrossOrigin
@RestController
public class TestController {
@GetMapping("/11")
public void testException(ModelMap modelMap, @ModelAttribute("author") String author22) {
String author = (String) modelMap.get("author");
System.out.println(author);
System.out.println("===" + author22);
throw new RestMessageException(ResponseStateEnum.AUTH_ERROR, "未授权");
}
}
-------------
控制台:
Gavin-test
===Gavin-test
请求返回:{"msg":"未授权","code":403}
碧色配置参考:
/**
* Author: mooner
* Date: 18-12-7
*/
@ControllerAdvice
public class Controller {
@Value("${system.style.host}")
private String styleHost;
@Value("${system.style.version}")
private int styleVersion;
@Value("${system.order.style.host}")
private String createOrderStyleHost;
@ModelAttribute
public void populateModel(Model model, HttpServletRequest req) {
model.addAttribute("styleHost", styleHost);
model.addAttribute("styleVersion", DateTimeUtils.getIntToday() + "" + styleVersion);
model.addAttribute("styleVersionNum", styleVersion);
model.addAttribute("createOrderStyleHost", createOrderStyleHost);
// model.addAttribute("loginUser", HTTPUtils.getSesssion(req));
}
@ExceptionHandler(BindException.class)
public @ResponseBody
String handBindException(BindException e) {
return new JSONObject()
.fluentPut("status", "0")
.fluentPut("msg", "参数错误")
.toJSONString();
}
@ExceptionHandler(AppException.class)
public String handNotFoundException(HttpServletResponse httpServletResponse, Model model, AppException e) {
httpServletResponse.setStatus(e.getState());
model.addAttribute("message", e.getMessage());
return "error";
}
}