These notes cover Error Handling in React Native when working with a backend like Appwrite, focusing on "throwing" errors from a global context and "catching" them in individual screens to update the UI.


1. The "Throw & Catch" Pattern

When using a service like Appwrite, errors often happen inside your Context (logic layer). Instead of just logging them to the console, you must throw them so the UI component knows something went wrong.

In UserContext.jsx

./contexts/UserContext.jsx

Replace console.log(error) with throw error. This propagates the error up to the component that called the function.

async function register(email, password) {
  try {
    await account.create(ID.unique(), email, password);
    await login(email, password);
  } catch (error) {
    // Throw the error so the Register screen can 'catch' it
    throw error; 
  }
}

2. Managing Error State in Screens

Each screen (Login/Register) needs its own local state to track if an error exists.

./app/(auth)/login.jsx (or ./app/(auth)/register.jsx)

const [error, setError] = useState(null);

const handleSubmit = async () => {
  setError(null); // Step 1: Reset before trying again
  try {
    await login(email, password);
  } catch (err) {
    setError(err.message); // Step 2: Capture the message
  }
};

3. Conditional Rendering of Errors

Use the short-circuit operator (&&) to show the error message only when the state is not null.

./app/(auth)/login.jsx