npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ortense/attempt

v0.3.0

Published

A minimalist TypeScript library for safe error handling using the Result Type pattern

Readme

Attempt banner - the attempt mascot generated by dall-e 2

@ortense/attempt

npm Coverage Status Made with Love

Uma biblioteca TypeScript minimalista para tratamento seguro de erros usando o padrão Result Type.

Instalação

npm install @ortense/attempt  # npm
yarn add  @ortense/attempt    # yarn
pnpm add @ortense/attempt     # pnpm
bun add @ortense/attempt      # bun

Por que usar?

  • 🎯 Type-safe: Tratamento de erros com segurança de tipos
  • 🎨 Elegante: API simples e expressiva
  • 🔒 Seguro: Sem exceções não tratadas
  • 🪶 Leve: Zero dependências
  • 📦 Pequeno: Bundle size mínimo
  • 💪 Robusto: 100% testado

Uso Básico

import { attempt, attemptAsync } from '@ortense/attempt'

// Código síncrono
const result = attempt(() => {
  const number = parseInt("123")
  if (isNaN(number)) throw new Error("Número inválido")
  return number
})

if (result.success) {
  console.log(result.value) // 123
} else {
  console.error(result.error) // Error
}

// Código assíncrono
const result = await attemptAsync(
  fetch("https://api.example.com/data")
    .then(response => response.json())
)

if (result.success) {
  console.log(result.value) // dados da API
} else {
  console.error(result.error.message) // "Falha na API"
}

API

Tipos

type Success<T> = {
  success: true
  value: T
}

type Failure<E extends Error> = {
  success: false
  error: E
}

type Result<T, E extends Error> = Success<T> | Failure<E>

type Match<T, E extends Error> = {
  success: (value: T) => void;
  failure: (error: E) => void;
}

Funções

success<T>(value: T): Success<T>

Cria um resultado de sucesso contendo um valor.

const result = success(42)
// { success: true, value: 42 }

match<T, E extends Error>(result: Result<T, E>, match: Match<T, E>): void

Executa diferentes callbacks baseados no estado do resultado.

match(result, {
  success: (value) => {
    console.log("Sucesso:", value)
  },
  failure: (error) => {
    console.error("Falha:", error)
  }
})

failure<E extends Error>(error: unknown): Failure<E>

Cria um resultado de falha contendo um erro.

const result = failure(new Error("Algo deu errado"))
// { success: false, error: Error("Algo deu errado") }

// Strings são convertidas para Error
const result = failure("Algo deu errado")
// { success: false, error: Error("Algo deu errado") }

attempt<T, E extends Error>(fn: () => T): Result<T, E>

Executa uma função e captura qualquer erro lançado.

const result = attempt(() => {
  if (Math.random() > 0.5) throw new Error("Azar!")
  return "Sorte!"
})

if (result.success) {
  console.log(result.value) // "Sorte!"
} else {
  console.error(result.error) // Error("Azar!")
}

attemptAsync<T, E extends Error>(Promise<T>): Promise<Result<T, E>>

Resolve uma promise e captura qualquer erro lançado.

const result = await attemptAsync(
  fetch("https://api.example.com/data")
    .then(response.json())
)

if (result.success) {
  console.log(result.value) // dados da API
} else {
  console.error(result.error) // "Falha na API"
}

Exemplos Avançados

Erros Customizados

class ApiError extends Error {
  constructor(
    message: string,
    public statusCode: number
  ) {
    super(message)
    this.name = "ApiError"
  }
}

const result = attempt(() => {
  throw new ApiError("Não autorizado", 401)
})

if (!result.success) {
  console.log(result.error.statusCode) // 401
}

Type Narrowing

function processResult(result: Result<number, Error>) {
  if (result.success) {
    // TypeScript sabe que result.value é number
    return result.value * 2
  } else {
    // TypeScript sabe que result.error é Error
    return result.error.message
  }
}

Composição de Operações

const getUser = async (id: string) => {
  const result = await attemptAsync(
    fetch(`/api/users/${id}`)
      .then(response => {
        if (!response.ok) throw new Error("Usuário não encontrado")
        return response
      })
      .then(response => response.json())
  )

  if (!result.success) {
    return result // early return com o erro
  }

  // Processa apenas em caso de sucesso
  return attempt(() => {
    const user = result.value
    if (!user.active) throw new Error("Usuário inativo")
    return user
  })
}

// Usando map para uma composição mais limpa
const getUserName = async (id: string) => {
  const result = await attemptAsync(
    fetch(`/api/users/${id}`)
      .then(response => {
        if (!response.ok) throw new Error("Usuário não encontrado")
        return response
      })
      .then(response => response.json())
  )

  return result.map(user => user.name)
}

Licença

MIT © Marcus Ortense