|
1 | 1 | # Error handling |
2 | 2 |
|
| 3 | +All `AsyncStorage` methods throw a specialized error type, `AsyncStorageError`. |
| 4 | +This class extends the standard `Error` class, by adding a `type` property to help identify the issue. |
3 | 5 |
|
4 | | -todo |
| 6 | +## Error types |
| 7 | + |
| 8 | +The error type is an enum `AsyncStorageError.Type` with the following possible values: |
| 9 | + |
| 10 | + |
| 11 | +### NativeModuleError |
| 12 | + |
| 13 | +Raised when the RN native module itself fails — for example, |
| 14 | +the module is null at app startup, or not initialized correctly. |
| 15 | + |
| 16 | + |
| 17 | +### WebStorageError |
| 18 | + |
| 19 | +Web only, when an IndexedDB operation fails. |
| 20 | +[See IndexedDB error codes](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error. |
| 21 | + |
| 22 | + |
| 23 | +### SqliteStorageError |
| 24 | + |
| 25 | +Raised when SQLite itself fails on iOS, macOS, or Android. |
| 26 | +[See SQLite error codes](https://www.sqlite.org/rescode.html). |
| 27 | + |
| 28 | + |
| 29 | +### OtherStorageError |
| 30 | + |
| 31 | +Raised for other storage-related failures that don’t fit into the categories above. |
| 32 | +Examples include: |
| 33 | + |
| 34 | +- Storage not initialized correctly |
| 35 | + |
| 36 | +- Corrupt or misformatted data returned from native code |
| 37 | + |
| 38 | +- Legacy storage exceptions (any error thrown by v2 implementation falls here) |
| 39 | + |
| 40 | +### UnknownError |
| 41 | +A catch-all for cases where the system cannot classify the error. |
| 42 | + |
| 43 | + |
| 44 | +## Example of error handling |
| 45 | + |
| 46 | + |
| 47 | +```typescript |
| 48 | +import { createAsyncStorage, AsyncStorageError } from "@react-native-async-storage/async-storage"; |
| 49 | + |
| 50 | +const storage = createAsyncStorage("user"); |
| 51 | + |
| 52 | +try { |
| 53 | + await storage. setItem( "email", "[email protected]"); |
| 54 | +} catch (e) { |
| 55 | + if (e instanceof AsyncStorageError) { |
| 56 | + switch (e.type) { |
| 57 | + case AsyncStorageError.Type.SqliteStorageError: |
| 58 | + console.error("SQLite failure:", e.message); |
| 59 | + break; |
| 60 | + case AsyncStorageError.Type.WebStorageError: |
| 61 | + console.error("IndexedDB failure:", e.message); |
| 62 | + break; |
| 63 | + default: |
| 64 | + console.error("AsyncStorage error:", e.message); |
| 65 | + } |
| 66 | + } else { |
| 67 | + console.error("Unexpected error:", e); |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments