Quick Start Guide

Get up and running with go-errors in minutes with this quick start guide.

This guide provides a rapid introduction to go-errors, demonstrating its core functionalities and basic usage patterns in just a few minutes. By the end of this guide, you'll be able to start using go-errors for both synchronous and asynchronous error handling in your projects.

Prerequisites

Before you begin, ensure that you have go-errors installed in your project. If you haven't installed it yet, please follow the Installation Guide.

Basic Usage

Let's dive into the basic usage of go-errors with practical examples.

Synchronous Operations with goSync

For synchronous operations that might throw errors, use the goSync function. Here’s a simple example of a division function that throws an error when dividing by zero:

import { goSync } from 'go-errors';

function divide(a: number, b: number): number {
  if (b === 0) {
    throw new Error("Cannot divide by zero!");
  }
  return a / b;
}

// Using goSync to handle potential errors
let [result, err] = goSync(() => divide(10, 2)); // Example of a successful operation

if (err) {
  // Error handling block
  console.error("Operation failed:", err.message);
} else {
  // Success block
  console.log("Result of division:", result); // Output: Result of division: 5
}

// Example of an operation that will throw an error
let [errorResult, divisionError] = goSync(() => divide(5, 0));

if (divisionError) {
  console.error("Division error caught:", divisionError.message); // Output: Division error caught: Cannot divide by zero!
} else {
  console.log("Division result:", errorResult);
}

In this example, goSync wraps the divide function. If divide executes successfully, the result is returned in the result variable, and err is null. If an error is thrown, result is null, and err contains the error object.

Asynchronous Operations with go

For asynchronous operations, such as Promises, use the go function. Let's consider an example using fetch to get user data from an API:

import { go } from 'go-errors';

interface User {
  id: string;
  name: string;
  email: string;
}

async function fetchUser(userId: string): Promise<User> {
  const response = await fetch(`/api/users/${userId}`);
  if (!response.ok) {
    throw new Error(\`HTTP error! status: ${response.status}\`);
  }
  return response.json() as Promise<User>;
}

async function main() {
  // Example of fetching user data successfully
  let [userData, userError] = await go(fetchUser('123'));

  if (userError) {
    console.error("Failed to fetch user data:", userError.message);
  } else {
    console.log("User data fetched:", userData);
  }

  // Example of handling a fetch error
  let [errorData, fetchError] = await go(fetchUser('invalid-user-id')); // Assuming this ID will cause an error

  if (fetchError) {
    console.error("Fetch operation error:", fetchError.message); // Output: Fetch operation error: HTTP error! status: 404 (or similar)
  } else {
    console.log("Fetch result:", errorData);
  }
}

main();

The go function handles Promises and resolves to a Result tuple when the Promise settles. This allows you to use the same error-checking pattern for both synchronous and asynchronous code.

Next Steps

Congratulations! You've completed the Quick Start Guide and now understand the basics of using go-errors. To deepen your knowledge and explore more features, we recommend the following:

  • Core Concepts: Explore the fundamental concepts behind go-errors, such as Result types and error normalization.
  • API Reference: Dive into the detailed API documentation for all functions and types provided by go-errors.
  • Guides & Best Practices: Learn about advanced usage patterns, best practices, and error handling strategies.

Start using go-errors in your projects today and experience a more elegant and type-safe approach to error handling in TypeScript and JavaScript!