try-catch#
Bungkus kode yang mungkin gagal dengan try-catch agar script tidak berhenti total.
Example:
function proses() { try { const data = ambilDariApi(); tulisKeSheets(data); } catch (err) { Logger.log('Gagal proses: ' + err.message); GmailApp.sendEmail(Session.getActiveUser().getEmail(), 'Script error', err.stack); }}Stack Trace#
err.stack berisi baris penyebab error. Berguna untuk debug.
Example:
catch (err) { Logger.log(err.stack); // menunjukkan urutan pemanggilan}Log Terstruktur#
Gunakan objek agar log mudah dibaca.
Example:
function logStep(step, data) { Logger.log(JSON.stringify({ step: step, waktu: new Date(), data: data }));}Mode Debug#
- Buka Executions di editor untuk melihat setiap jalannya fungsi.
- Gunakan Breakpoint di editor (klik margin kiri) untuk menjeda per baris.
- Ganti
Logger.logsementara denganthrowuntuk menghentikan di titik tertentu.
Validasi Input#
Example:
function olahBaris(r) { if (!r || r.length < 2) { Logger.log('Baris tidak valid, dilewati'); return; } // lanjut proses}Stackdriver / Cloud Logging#
Untuk script terhubung ke Cloud Project, console.log muncul di Google Cloud Logging (bisa filter, periksa histori lama).
| Teknik | Kegunaan |
|---|---|
try-catch | Cegah berhenti total |
err.stack | Lacak sumber error |
| Breakpoint | Debug per baris |
| Executions | Riwayat jalannya fungsi |
| Cloud Logging | Log jangka panjang |
Warning
Jangan biarkan
catchkosong (catch(e){}). Error akan tersembunyi dan sulit dilacak.
Next#
Pelajari Library & Modularisasi.