数据抛异常类的用法(exception)

因为数据库有异常的数据增删改查都会造成数据库挂掉 后端就没有返回请求,造成前端一直在等待结果 为了避免这种情况 所以要对数据进行处理,先前端筛选,后端筛选(防止不经前端暴力数据注入)

异常类的抛出不许要带返回请求,因为本身就是个返回值!!!

Exception 类及其子类是 Throwable 的一种形式,它指出了合理的应用程序想要捕获的条件。

构造方法

Exception(String message) 
          构造带指定详细消息的新异常。

自己写个异常类

public class LoginException extends  Exception{
          
   
    public LoginException() {
          
   
    }
//    继承异常类抛出信息
    public LoginException(String message) {
          
   
        super(message);
    }
}

方法调用 throw new LoginException(异常信息);

public Accounts login(Accounts accounts) throws LoginException {
          
   
//        判断是为空和是否有空格
        if(accounts.getUsername()==null||"".equals(accounts.getUsername().trim())){
          
   
            throw  new LoginException("用户名不能为空");
        }
        if(accounts.getPassword()==null||"".equals(accounts.getPassword().trim())){
          
   
            throw  new LoginException("密码不能为空");
        }
        String pattern="^[\w]{6,16}";
        if(!accounts.getPassword().matches(pattern)){
          
   
            throw new LoginException("密码不符合规范");
        }
        Accounts accounts1=new AccountsDaoImpl().query(accounts);
        if (accounts1!=null){
          
   
            return accounts1;
        }else {
          
   
            throw  new LoginException("登录失败!");
        }
    }

数据进入service层后进行异常捕获 try{ 数据 }catch((LoginException e){ e.printStackTrace(); System.out.println(e.getMessage());()把service层逻辑判断结果日志调用出来应答前端请求 }

public void login() {
          
   
        Accounts accounts=new Accounts("king","a866971331");
        try {
          
   
            Accounts accounts1=new LoginServiceImpl().login(accounts);
            System.out.println("登录成功,id="+accounts1.getId());
        } catch (LoginException e) {
          
   
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

数据抛异常类的好处在于保证返回值是索要的结果(不携带多余判定结果),能保证返回类型不会改变

经验分享 程序员 微信小程序 职场和发展