Async/Await Error Handling
Penjelasan
Express (versi 4 ke bawah) TIDAK otomatis menangkap error dari Promise yang di-reject di dalam handler async — kalau tidak ditangani manual lewat try/catch, aplikasinya bisa crash tanpa pesan error yang jelas ke client. Pola umum: bungkus handler async dengan try/catch dan next(error), atau pakai helper wrapper supaya tidak perlu menulis try/catch berulang di tiap handler.
Contoh Konsep
// Cara manual, try/catch di tiap handler (repetitif):
app.get('/produk/:id', async (req, res, next) => {
try {
const produk = await Produk.findById(req.params.id);
res.json(produk);
} catch (error) {
next(error); // teruskan ke error handling middleware
}
});
// Cara lebih ringkas dengan wrapper:
function asyncHandler(fn) {
return (req, res, next) => fn(req, res, next).catch(next);
}
app.get('/artikel/:id', asyncHandler(async (req, res) => {
const artikel = await Artikel.findById(req.params.id);
res.json(artikel);
}));
Praktikum
Buat fungsi wrapper asyncHandler(fn) seperti dicontohkan. Pakai untuk membungkus route GET /kategori/:id yang (secara konsep) memanggil Kategori.findById(req.params.id) secara async.
Ketik/edit bebas di sini untuk latihan — kode ini tidak dijalankan.
Tips
Express versi 5 (rilis lebih baru) SUDAH otomatis menangkap error dari handler async tanpa perlu try/catch atau wrapper manual — tapi banyak project masih memakai Express 4, jadi penting tetap paham pola manual ini sampai migrasi ke versi 5 jadi standar.