【Java】项目开发(三)不要让用户看到你的系统异常

草稿里放了很久,把这个以前写的小项目捞出来。

一切尽在注释里~

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();
    }

很繁琐,当你要写登录的时候也要重复上面步骤吗?如何简化?
请看下一篇文章

如有错误,还请多多指教!
转载或者引用本文内容请注明来源及原作者:橘足轻重;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值