Saltar al contenido
Skillpedia
Programación general48 mil · #4641

fp-either-ref

Qué hace

Esta herramienta te ayuda a gestionar los errores de los programas de forma ordenada. Te permite saber si algo ha salido bien (con un valor) o ha fallado (con un mensaje de error concreto), sin que el programa se bloquee de forma inesperada.

Cuándo usarla

  • ✓Cuando necesitas comprobar que los datos son correctos antes de usarlos.
  • ✓Cuando realizas una operación que puede fallar, como leer un archivo.
  • ✓Para convertir código que puede lanzar errores en un formato que el programa entienda como 'éxito' o 'fallo'.

Link de la skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-either-ref/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-either-ref/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo comprobar si un correo electrónico es válido y, si no lo es, mostrar un mensaje de error claro?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Funciona definiendo dos caminos: uno para el éxito (con el resultado esperado) y otro para el fallo (con la descripción del problema). Después puedes elegir qué camino seguir según el resultado.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

Either Quick Reference

Either = success or failure. Right(value) or Left(error).

When to Use

  • You need a quick fp-ts reference for typed synchronous error handling.
  • The task involves validation, fallible operations, or converting throwing code to Either.
  • You want a compact cheat sheet rather than a long tutorial.

Create

import * as E from 'fp-ts/Either'

E.right(value)           // Success
E.left(error)            // Failure
E.fromNullable(err)(x)   // null → Left(err), else Right(x)
E.tryCatch(fn, toError)  // try/catch → Either

Transform

E.map(fn)                // Transform Right value
E.mapLeft(fn)            // Transform Left error
E.flatMap(fn)            // Chain (fn returns Either)
E.filterOrElse(pred, toErr) // Right → Left if pred fails

Extract

E.getOrElse(err => fallbackValue)  // Get Right or default
E.match(onLeft, onRight)     // Pattern match
E.toUnion(either)            // E | A (loses type info)

Common Patterns

import { pipe, identity } from 'fp-ts/function'
import * as E from 'fp-ts/Either'

// Toy validation; an @ check is not complete email validation
const validateEmail = (s: string): E.Either<string, string> =>
  s.includes('@') ? E.right(s) : E.left('Invalid email')

// Chain validations (stops at first error)
pipe(
  E.right({ email: 'test@example.com', age: 25 }),
  E.flatMap(d => pipe(validateEmail(d.email), E.map(() => d))),
  E.flatMap(d => d.age >= 18 ? E.right(d) : E.left('Must be 18+'))
)

// Convert throwing code
const parseJson = (s: string) => E.tryCatch(
  () => JSON.parse(s),
  (e) => `Parse error: ${e}`
)

vs try/catch

// ❌ try/catch - errors not in types
try {
  const data = JSON.parse(input)
  process(data)
} catch (e) {
  handleError(e)
}

// ✅ Either - errors explicit in types
pipe(
  E.tryCatch(() => JSON.parse(input), String),
  E.flatMap(data => E.tryCatch(() => process(data), String)),
  E.match(handleError, identity)
)

Use Either when error type matters and you want to chain operations.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Reference scope

These are fp-ts 2.x fragments. Supply application variables, types, validators and imports, and check the installed version. map does not catch thrown exceptions. Task has no typed error channel; an improperly wrapped promise can still reject. Use tryCatch at fallible boundaries.

Official API: fp-ts modules.

Preguntas frecuentes

¿Cuál es la diferencia entre 'Right' y 'Left'?

'Right' representa el éxito y contiene el valor que esperabas. 'Left' representa el fallo y contiene el mensaje o el tipo de error que se ha producido.

¿Puedo usar esto con código que puede lanzar errores (como leer un archivo)?

Sí, la herramienta tiene una función concreta (`tryCatch`) que convierte las operaciones que pueden causar errores en un resultado 'Right' (éxito) o 'Left' (fallo).

¿Cómo obtengo el resultado final si puede ser un éxito o un error?

Puedes usar funciones como `getOrElse`, que da un valor por defecto si se produce un error, o `match`, que ejecuta acciones distintas según haya sido un éxito o un error.

Detalles

Descripción original del autor

Quick reference for Either type. Use when user needs error handling, validation, or operations that can fail with typed errors.

repo: sickn33/agentic-awesome-skills

Popularidad

Estrellas en GitHub
48 mil
Posición en el ranking
#4641
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas