代码结构:
统一返回类:
public class DefaultResult implements Serializable { private static final long serialVersionUID = -8166394979459023084L; public static final int CODE_SUCCESS = 0; public static final int CODE_ERROR = 1; public static final String STR_SUCCESS = "SUCCESS"; public static final String STR_ERROR = "ERROR"; private int code = DefaultResult.CODE_SUCCESS; private String msg = DefaultResult.STR_SUCCESS; private T Data;//省略构造函数、get/set、toString}
全局Exception:
public class GlobalException extends Exception { private static final long serialVersionUID = 6208687918940925747L; private int errorCode; private String errorStr;//省略构造函数、get/set、toString}
全局异常处理类:
@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(value = GlobalException.class) @ResponseBody public DefaultResult errorJson(GlobalException e) { DefaultResult result = new DefaultResult<>(); result.setCode(e.getErrorCode()); result.setMsg(e.getErrorStr()); result.setData(""); return result; }}
测试用结果类:
public class UserResult implements Serializable { private static final long serialVersionUID = 984326944850108129L; private long id; private String userName;/省略构造函数、get/set、toString}
Controller:
@RestControllerpublic class HelloController { @RequestMapping("/hello") public DefaultResult hello( @RequestParam(value = "type", required = false) String type) throws GlobalException { if (Objects.nonNull(type) && type.equals("error")) { throw new GlobalException(666, "人为错误"); } else { UserResult ur = new UserResult(); ur.setId(111); ur.setUserName("测试"); DefaultResult result = new DefaultResult(); result.setData(ur); return result; } }}
结果: