You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLite中记录错误回调?React Native连接数据库时显示错误信息

嘿,我来帮你搞定这两个问题!

解决React Native SQLite错误回调的显示与记录问题

一、在errorCB中显示错误信息

你当前的代码有两个小问题需要调整,才能正确获取并显示错误信息:

  1. 调用openDatabase时,回调函数不要加括号(this.successCB()会立即执行函数,而不是传递引用给SQLite库)
  2. errorCB没有接收错误参数——react-native-sqlite-storage的错误回调会自动传入一个包含错误详情的对象,我们可以利用这个对象获取具体错误信息

修改后的代码示例:

import SQLite from 'react-native-sqlite-storage';

// 注意:回调只传函数引用,不要加()
var db = SQLite.openDatabase(
  {name: "banco.db", createFromLocation: 1},
  this.successCB,
  this.errorCB
);

// 让errorCB接收error参数
errorCB(error) {
  // 先打印错误到控制台方便调试
  console.error('数据库出错啦:', error);
  // 将错误信息更新到state中展示给用户
  this.setState({
    message: `数据库错误: ${error.message} (错误码: ${error.code})`
  });
}

successCB() {
  this.setState({message: "SQL executed fine"});
}

另外要注意this的指向问题,如果是在类组件中,建议在构造函数里绑定回调的this,或者用箭头函数定义回调:

// 类组件构造函数中绑定this
constructor(props) {
  super(props);
  this.state = { message: '' };
  this.errorCB = this.errorCB.bind(this);
  this.successCB = this.successCB.bind(this);
}

// 或者用箭头函数定义回调,自动绑定this
const errorCB = (error) => {
  console.error('数据库出错啦:', error);
  this.setState({
    message: `数据库错误: ${error.message} (错误码: ${error.code})`
  });
};

二、记录SQLite错误回调的方法

根据你的需求,可以选择以下几种方式记录错误:

  • 控制台打印(调试阶段):直接用console.error打印错误详情,开发时能快速排查问题,就是上面代码里做的那样。
  • 存入本地数据库:如果需要持久化保存错误记录,可以创建一个专门的错误日志表,在errorCB中插入错误信息:
    errorCB(error) {
      console.error('数据库出错啦:', error);
      // 确保数据库实例存在后,插入错误日志
      if (db) {
        db.transaction((tx) => {
          // 先创建错误日志表(不存在则创建)
          tx.executeSql(
            'CREATE TABLE IF NOT EXISTS error_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, error_message TEXT, error_code INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)',
            [],
            () => {
              // 插入错误记录
              tx.executeSql(
                'INSERT INTO error_logs (error_message, error_code) VALUES (?, ?)',
                [error.message, error.code],
                () => console.log('错误日志已保存'),
                (tx, err) => console.error('保存错误日志失败:', err)
              );
            },
            (tx, err) => console.error('创建错误日志表失败:', err)
          );
        });
      }
      this.setState({
        message: `数据库错误: ${error.message} (错误码: ${error.code})`
      });
    }
    
  • 存入AsyncStorage:如果不想用数据库存储,也可以用AsyncStorage保存错误日志数组:
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    errorCB(error) {
      console.error('数据库出错啦:', error);
      // 构造错误日志对象
      const errorLog = {
        message: error.message,
        code: error.code,
        timestamp: new Date().toISOString()
      };
      // 读取现有日志并添加新日志
      AsyncStorage.getItem('sqlite_error_logs')
        .then(logs => {
          const existingLogs = logs ? JSON.parse(logs) : [];
          existingLogs.push(errorLog);
          return AsyncStorage.setItem('sqlite_error_logs', JSON.stringify(existingLogs));
        })
        .then(() => console.log('错误日志已保存到本地'))
        .catch(err => console.error('保存日志失败:', err));
      
      this.setState({
        message: `数据库错误: ${error.message} (错误码: ${error.code})`
      });
    }
    
  • 上报到远程服务器:如果是生产环境,可以在errorCB中调用后端API,把错误信息发送到服务器,方便监控和批量排查问题。

内容的提问来源于stack exchange,提问作者Italo Rodrigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:55:57