最近在写一个小项目,当我登录的时候发现会产生一些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;
}