草稿里放了很久,把这个以前写的小项目捞出来。
一切尽在注释里~
util类
@Setter
@Getter
@NoArgsConstructor
public class JsonResult<T> {
public static final int CODE_SUCCESS = 200;
public static final String MSG_SUCCESS = "操作成功";
public static final int CODE_NOLOGIN = 401;
public static final String MSG_NOLOGIN = "请先登录";
public static final int CODE_ERROR = 500;
public static final String MSG_ERROR = "系统异常,请联系管理员";
private int code; //区分不同结果, 而不再是true或者false
private String msg;
private T data; //除了操作结果之后, 还可以携带数据返回
public JsonResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static <T> JsonResult success(T data) {
return new JsonResult(CODE_SUCCESS, MSG_SUCCESS, data);
}
public static JsonResult success() {
return new JsonResult(CODE_SUCCESS, MSG_SUCCESS, null);
}
public static <T> JsonResult error(int code, String msg, T data) {
return new JsonResult(code, msg, data);
}
public static JsonResult defaultError() {
return new JsonResult(CODE_ERROR, MSG_ERROR, null);
}
exception类
/**
* 自定义异常,给用户提示的异常
* 用户异常
*/
public class LogicException extends RuntimeException{
public LogicException(String message){
super(message);
}
}
controller类
@PostMapping("/regist")
public Object regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
try {
userInfoService.regist(phone, nickname, password, rpassword, verifyCode);
} catch (LogicException e) {
//添加自定义的用户异常类,here是解决方案
e.printStackTrace();
return JsonResult.error(JsonResult.CODE_ERROR_PARAM, e.getMessage(), null);
} catch (Exception e) {
e.printStackTrace();
//return JsonResult.error(JsonResult.CODE_ERROR_PARAM,
//此操作存在问题,虽然给用户看的异常可以抓到,但是如果有系统异常一样也会被抓到,然而项目开发并不允许给用户看系统异常
//解决方案:抓自定义的用户异常类,剩下的就是系统异常,用于区分用户异常跟系统异常
return JsonResult.defaultError();
}
return JsonResult.success();
}
很繁琐,当你要写登录的时候也要重复上面步骤吗?如何简化?
请看下一篇文章
如有错误,还请多多指教!
转载或者引用本文内容请注明来源及原作者:橘足轻重;