Để tạo loại lỗi tùy chỉnh, hãy extends Error. Best practice: gọi super(message), đặt this.name tên lớp lỗi, có thể thêm thuộc tính tùy chỉnh (code, status...).
Ví dụ
Tạo CustomError kế thừa Error:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Kế thừa Error JS</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
</style>
</head>
<body>
<h1>Kế thừa lớp Error trong JavaScript</h1>
<div class="result"></div>
<button class="Btn">TẠO LỖI TÙY CHỈNH</button>
<h3>Nhấn nút để ném và bắt CustomError</h3>
<script>
const resEle = document.querySelector(".result");
const btn = document.querySelector(".Btn");
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
function test() { throw new CustomError("Lỗi tùy chỉnh mới"); }
btn.addEventListener("click", () => {
try {
test();
} catch (err) {
resEle.innerHTML = `err.name = ${err.name}<br>`;
resEle.innerHTML += `err.message = ${err.message}<br>`;
resEle.innerHTML += `err instanceof Error: ${err instanceof Error}<br>`;
resEle.innerHTML += `err instanceof CustomError: ${err instanceof CustomError}`;
}
});
</script>
</body>
</html>
Kết quả
Hiển thị: name, message, và xác nhận instanceof Error = true, instanceof CustomError = true.
Mẹo: Thêm Error.captureStackTrace(this, this.constructor) trong constructor để stack trace trỏ đúng chỗ (Node.js).