当前位置: 代码网 > it编程>编程语言>Java > SpringBoot前后端交互、全局异常处理之后端异常信息抛到前端显示弹窗

SpringBoot前后端交互、全局异常处理之后端异常信息抛到前端显示弹窗

2024年08月09日 Java 我要评论
前提是前端必须有接收后端信息的载体:比如:ajax的异步接收等等。后端:编写后端的统一返回信息类:/** * 后端统一返回结果 * @param <t> */@datapublic cla

前提是前端必须有接收后端信息的载体:比如:ajax的异步接收等等。

后端:

编写后端的统一返回信息类:

/**
 * 后端统一返回结果
 * @param <t>
 */
@data
public class result<t> implements serializable {
    private integer code;//1成功,0和其他数字为失败。
    private string msg;//错误信息
    private t data;//数据

    public static <t> result<t> success(){
        result<t> result = new result<t>();
        result.code=1;
        return result;
    }
    public static <t> result<t> success(t object){
        result<t> result = new result<t>();
        result.data=object;
        result.code=1;
        return result;
    }

    public static <t> result<t> error(string msg){
        result<t> result = new result<t>();
        result.code=0;
        result.msg=msg;
        return result;
    }
}

异常基础类:

/**
 * 业务异常
 */
public class baseexception extends runtimeexception{
    public baseexception(string message) {
        super(message);
    }
    public baseexception() {
    }
}

 账号不存在异常:

/**
 * 账号不存在异常
 */
public class accountnotfoundexception extends baseexception {

    public accountnotfoundexception() {
    }

    public accountnotfoundexception(string msg) {
        super(msg);
    }

}

账号密码为空异常: 

/**
 * 账号密码为空
 */
public class inputaccountandpassword extends baseexception{
    public inputaccountandpassword(string message) {
        super(message);
    }
}

 登录失败异常:

/**
 * 登录失败
 */
public class loginfailedexception extends baseexception{
    public loginfailedexception(string msg){
        super(msg);
    }
}

 密码错误:

/**
 * 密码错误异常
 */
public class passworderrorexception extends baseexception {

    public passworderrorexception() {
    }

    public passworderrorexception(string msg) {
        super(msg);
    }

}

全局异常类:

/**
 * 全局异常处理
 */
//@controlleradvice(annotations = {restcontroller.class,controller.class})
//@responsebody
@slf4j
@restcontrolleradvice
public class globalexceptionhandler {
    /**
     * 业务异常
     * @param ex 异常信息
     * @return 封装、抛出给前端
     */
    @exceptionhandler
    public result<string> exceptionhandler(baseexception ex){
        log.error(ex.getmessage());
        return result.error(ex.getmessage());
    }

    @exceptionhandler
    public result<string> exceptionhandler(expiredjwtexception ex){
        string message=ex.getmessage();
        if (message.contains("expired")){
            return result.error("登录过期!");
        }
        return null;
    }
}

举例:

登录的服务

@service
@slf4j
public class loginserviceimpl implements loginservice {
    @autowired(required = false)
    private loginmapper loginmapper;

    /**
     * 用户登录
     * @param user 用户
     */
    public void userlogin(user user) {
        string email = user.getemail();
        string password = user.getpassword();
        if (email.isempty() || password.isempty()) {
            //账号密码为空
            throw new inputaccountandpassword(messageconstant.account_password_empty);
        }
        //账号密码不为空
        else {
            //验证账号
            int i = loginmapper.userexist(email);
            //账号存在
            if (i > 0) {
                //验证密码
                int p = loginmapper.logincheck(email, password);
                //密码正确
                if (p == 1) {
                    //准许登录 state==1
                    loginmapper.login(email);
                }
                else {
                    //密码错误
                    throw new passworderrorexception(messageconstant.password_error);
                }
            }
            //账号不存在
            else {
                throw new accountnotfoundexception(messageconstant.account_not_found);
            }
        }
    }
}

异常提示常量类messageconstant:

/**
 * 信息提示常量类
 */
public class messageconstant {
    public static final string password_error = "密码错误";
    public static final string account_not_found = "账号不存在";
    public static final string login_failed = "登录失败";
    public static final string account_password_empty="请输入账号和密码";
}

控制端:

@restcontroller
@requestmapping("/login")
@slf4j
public class logincontroller {
    @autowired(required = false)
    private loginservice loginservice;
    @autowired
    private jwtproperties jwtproperties;
    @postmapping("/userlogin")
    public result login(@requestbody user user){
        log.info("开始登录:email:{},password:{}",user.getemail(),user.getpassword());
        log.info("{}",user);
        loginservice.userlogin(user);
        //登录成功后,生成jwt令牌
        map<string, object>claims=new hashmap<>();
        claims.put("userid",1l);
        claims.put("email",user.getemail());
        string token= jwtutil.createjwt(
                jwtproperties.getusersecretkey(),
                jwtproperties.getuserttl(),
                claims);
        userdto userdto = new userdto();
        userdto.settoken(token);
        log.info("生成的token是:{}",token);
        return result.success(userdto);
    }
}

前端登录页面以及ajax的测试用例:

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>欢迎登录公司员工考勤管理平台</title>
    <link rel="shortcut icon" th:href="@{/images/icon.svg}" rel="external nofollow" >
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}" rel="external nofollow" >
    <script th:src="@{/js/jquery-3.2.1.js}"></script>
    <script th:src="@{/js/token.js}"></script>
    <script type="text/javascript">
        $(function () {
            let token=null;
            //登录按钮
            $("#login").click(function () {
                let email=$('#email').val();
                let password=$('#password').val();
                $.ajax({
                    type:"post",
                    url:"/login/userlogin",
                    contenttype:"application/json",
                    data:json.stringify({"email":email,"password":password}),
                    success:function (result) {
                        if (result.code===1){
                             token=result.data.token;
                            alert("登录成功");
                        //    收到token,开始存储token
                            localstorage.setitem('token',token);
                            alert("token值为:"+token+"!");
                            //返回token给后端
                            //返回后端
                            location.href="/main" rel="external nofollow" ;//也会经过拦截器
                        }else {
                            alert(result.msg);
                        }
                    }
                });
            });

         $("#registry").click(function () {
             location.href="/registry" rel="external nofollow" 
         })
        })
    </script>
</head>
<body style="position: absolute;
  top: 20%;
  left: 38%;
  transform: translate(40%,40%);
  margin: 0;padding: 0">
<div>
    <h2>登录页面</h2>
</div>
<div>
    <label for="email"></label><input type="text" id="email" name="email" placeholder="e-mail address">
</div>
<div>
    <label for="password"></label><input type="password" id="password" name="password" placeholder="password"/>
</div>
<button id="login">登录</button>
<button id="registry">注册</button>
</body>
</html>

测试:

账号密码不为空:

后台:

账号不存在:

后台:

密码错误:

后台:

还有很多其他的情况......

tips:其实有些情况可以直接在前端判断,没有必要全部都给到后台判断,这样会造成后台压力比较大;比如密码账号不为空,账号格式等等。

总结

到此这篇关于springboot前后端交互、全局异常处理之后端异常信息抛到前端显示弹窗的文章就介绍到这了,更多相关springboot后端异常信息抛到前端弹窗内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com