Error Handling
Error handling digunakan untuk menangani kesalahan yang mungkin terjadi dalam program:
try…catch
try {
// Kode yang mungkin menghasilkan error
const result = 10 / 0;
console.log(result);
} catch (error) {
// Menangani error
console.error("Terjadi error:", error.message);
}
Error Objects
try {
throw new Error("Ini adalah error custom");
} catch (error) {
console.error(error.name); // "Error"
console.error(error.message); // "Ini adalah error custom"
console.error(error.stack); // Stack trace
}
Custom Errors
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Input tidak valid");
} catch (error) {
if (error instanceof ValidationError) {
console.error("Error validasi:", error.message);
}
}
Error Propagation
function validateInput(input) {
if (!input) {
throw new Error("Input tidak boleh kosong");
}
return input;
}
try {
const result = validateInput("");
} catch (error) {
console.error("Error:", error.message);
}
Last updated on