-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12.js
More file actions
111 lines (89 loc) · 2.81 KB
/
12.js
File metadata and controls
111 lines (89 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Manejo de errores try/catch
async function cargarUsuario(id) {
try {
const respuesta = await fetch(`https://api2.escuelajs.co/api/v1/users/${id}`);
const usuario = await respuesta.json();
console.log(usuario.name);
} catch (error) {
console.error("error al cargar usuario",error.message);
}
}
cargarUsuario(1);
// Finally, limpieza garantizada
async function cargarPerfil(userId) {
mostrarSpinner();
try {
const respuesta = await fetch(`https://api.escuelajs.co/api/v1/users/${userId}`);
if (!respuesta.ok) {
throw new Error(`HTTP ${respuesta.status}: ${respuesta.statusText}`);
}
const perfil = await respuesta.json();
renderizarPerfil(perfil);
} catch (error) {
mostrarError(error.message);
} finally {
ocultarSpinner(); // Siempre se ejecuta — con o sin error
}
}
// Errores personalizados
async function obtenerProducto(id) {
try {
const respuesta = await fetch(`https://api.escuelajs.co/api/v1/products/${id}`);
// fetch no rechaza con errores HTTP 4xx o 5xx — hay que verificar
if (!respuesta.ok) {
throw new Error(`Producto no encontrado (${respuesta.status})`);
}
const producto = await respuesta.json();
if (!producto || !producto.id) {
throw new Error("Producto inválido o sin datos");
}
console.log(producto.title);
return producto;
} catch (error) {
console.error(error.message);
return null; // Valor por defecto ante el error
}
}
obtenerProducto(999);
// Múltiples try/catch: cuándo separarlos
async function procesarPedido(pedidoId) {
let usuario;
let inventario;
// Error al obtener usuario — crítico, no podemos continuar
try {
usuario = await obtenerUsuario(pedidoId);
} catch (error) {
throw new Error("No se pudo identificar al usuario"); // Relanza el error
}
// Error al obtener inventario — podemos continuar con stock por defecto
try {
inventario = await obtenerInventario();
} catch (error) {
console.warn("Inventario no disponible, usando caché");
inventario = obtenerInventarioCached();
}
return procesarConDatos(usuario, inventario);
}
// Con Promesas y .catch()
function cargarCategorias() {
return fetch("https://api.escuelajs.co/api/v1/categories")
.then(res => {
if (!res.ok) throw new Error(`Error ${res.status}`);
return res.json();
})
.then(datos => renderizar(datos))
.catch(error => mostrarError(error.message))
.finally(() => ocultarSpinner());
}
// Con async/await y try/catch — equivalente exacto
async function cargarCategorias() {
try {
const res = await fetch("https://api.escuelajs.co/api/v1/categories");
const datos = await res.json();
renderizar(datos);
} catch (error) {
mostrarError(error.message);
} finally {
ocultarSpinner();
}
}