如何解决登陆时用户名/密码不匹配的问题

最近在写一个小项目,当我登录的时候发现会产生一些bug。

1.密码为空

在这里插入图片描述

2.用户为空

在这里插入图片描述

3.二者都不为空,但是不匹配

在这里插入图片描述

4.那么,如何解决呢?

通过观察,我们发现这三种情况错误码都是500,即后台出现错误。
通过请教老师和查阅各种资料,发现可以利用springboot来解决异常问题。

4.1 自定义异常

/**
 *  定义系统异常
 */
public class AeipfException extends  RuntimeException{

    public AeipfException(String message) {
        super(message);
    }
}
/**
 * 和权限验证相关的异常
 */
public class AuthenticationException extends AeipfException {
    public AuthenticationException(String message) {
        super(message);
    }
}
/**
 * 用户名,密码不为空
 */
public class AccountNotNullException extends AuthenticationException{
    public AccountNotNullException(String message) {
        super(message);
    }
}
/**
 * 用户名不存在
 */
public class UsernameNotFoundException extends AuthenticationException{
    public UsernameNotFoundException(String message) {
        super(message);
    }
}
/**
 * 用户名和密码不匹配(用户名正确),即用户名或密码错误
 */
public class InvaildUserException extends AuthenticationException{
    public InvaildUserException(String message) {
        super(message);
    }
}

4.2 定义异常处理类

package com.dyit.aeipf.service.exception.handler;

import com.dyit.aeipf.common.dto.HttpResp;
import com.dyit.aeipf.common.dto.RespEnum;
import com.dyit.aeipf.service.exception.authentication.AccountNotNullException;
import com.dyit.aeipf.service.exception.authentication.InvaildUserException;
import com.dyit.aeipf.service.exception.authentication.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

//面向切面
@RestControllerAdvice
public class AuthenticationExceptionHandler {

    @ExceptionHandler
    public HttpResp usernameNotNull(AccountNotNullException e){
        return new HttpResp(RespEnum.LOGIN_USERNAME_NOT_NULL,null,new Date());
    }

    @ExceptionHandler
    public HttpResp usernameNotFound(UsernameNotFoundException e){
        return new HttpResp(RespEnum.LOGIN_USERNAME_NOT_FOUND,null,new Date());
    }

    @ExceptionHandler
    public HttpResp invaildUser(InvaildUserException e){
        return new HttpResp(RespEnum.LOGIN_INVALID,null,new Date());
    }
}

4.3 抛出异常

 @Override
    public Login loginCheck(String username, String password) {
        if (username==null||password==null) throw new AccountNotNullException("用户名或密码不能为空");
        //根据账号查询
        Login login = loginDao.findByUsername(username);
        if (login==null) throw new UsernameNotFoundException("用户名不存在");

        if (!password.equals(login.getPassword())) throw new InvaildUserException("用户名或密码错误");
        return login;
    }

5. 结果查看

5.1 密码为空

在这里插入图片描述

5.2 账号为空

在这里插入图片描述

5.3账号或密码错误

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值