Estoy haciendo algunas llamadas a la base de datos y estoy usando async/await y try/catch para el manejo de errores. Estoy luchando si debo tener todas las llamadas de db en un try/catch, or have multiple bloques de prueba/captura para cada llamada.
También tengo algunas llamadas en callback fncs, no estoy seguro de que esas llamadas se atrapen en mi bloque catch si solo tengo un try/catch . Con eso en mente, esas llamadas tienen su propio bloque try catch. Aquí hay un ejemplo de trabajo:
exports.syncStaff = async function (req, res, next) { // ShiftTask && Shift is a model from mongoose try { // DB CALL #1 --> Inside of Try/Catch Block const shift = await Shift.findById(req.params.id); // DB CALL #2 + 3 --> Two calls run in parallel --> Inside of Try/Catch Block const [shiftTasks, shiftType] = await Promise.all([ ShiftTask.find({ group: shift.id }), mongoose.model('ShiftType').findById(shift.type).populate('tasks').select('tasks') ]); await Promise.all(shiftTasks.filter(st => !shiftType.workshops.find(type => type.id.toString() === st.task.toString() || st.status !== 'pending')).map(task => { // DB CALL #4 --> Separate Try/Catch Block, is this needed? try { return ShiftTask.remove({ _id: task.id }); } catch (error) { console.error(error); next(error); } })); await Promise.all(shiftType.workshops.filter(type => !shiftTasks.find(task => task.shift.toString() === type.id.toString())).map(type => { try { // DB CALL #5 -- Separate Try/Catch Block, is this needed? return ShiftTask.create({ group: shift.id, eventType: type.id }); } catch (error) { console.error(error); next(error); } })); return await res.status(201).json('still to be decided'); } catch (error) { console.error(error); next(error); } };¿Son necesarios los bloques try/catch en las llamadas db #4 y #5?
No creo que se necesiten bloques de captura de prueba externos. Si se arroja un error desde algún lugar, se puede capturar desde el bloque en el contenedor público. Hice un ejemplo como este. Puede probar el segundo caso especificado en el código de la consola de Google Chrome.
let compPromise = new Promise(function(resolve, reject) { resolve('Complete'); }); let errPromise = new Promise(function(resolve, reject) { reject(new Error("Whoops promise reject!")) }); let exec = async () => { try { let res1 = await compPromise; console.log('res1', res1); let [res2,res3] = await Promise.all([ compPromise, compPromise ]) console.log('res2', res2); console.log('res3', res3); // In this case, reject will return from the promise and will catch it in the catch block. await Promise.all([10, 20, 30].map((x) => x === 30 ? errPromise : compPromise)) // In this case, the parameter was deliberately sent as undefined and will still be caught in the catch block. await Promise.all([undefined, 'Johnny', 'Alison'].map((x) => x.trim().includes("n") ? errPromise : compPromise)) } catch(err) { console.log(err.toString()); } } exec()