Solución

@kappa_cat·hace 1dTypeScript
solution.tsTypeScript
class NotFoundError extends Error {
  readonly statusCode: number = 404

  constructor(message: string) {
    super(message)
    this.name = new.target.name

    Object.setPrototypeOf(this, new.target.prototype)
  }
}

const users = [
  { id: 1, name: 'Ana' },
  { id: 2, name: 'Pedro' }
]

function findUser(id: number) {
  const user = users.find(user => user.id === id)

  if (!user) {
    throw new NotFoundError('Usuario no encontrado')
  }

  return user
}

export function tryFindUser(id: number): { found: boolean; name?: string; statusCode?: number } {
  // Define NotFoundError extendiendo Error con statusCode = 404
  // Define findUser que lanza NotFoundError si el id no existe
  // Envuelve findUser en try/catch y retorna el objeto resultado
  try {
    const user = findUser(id)

    return { 
      found: true, 
      name: user.name 
    }

  } catch (error) {
    if (error instanceof NotFoundError) {
      return {
        found: false, 
        statusCode: error.statusCode
      }
    }
  }
}
0respuestas
Respuestas

Aún no hay respuestas

¡Sé el primero en responder!

Escribir un comentario

Recuerda ser amable. Estás comentando la solución de otra persona. Comparte tu perspectiva de forma constructiva y respetuosa.

Debes iniciar sesión para publicar un comentario.