ใน Google Apps Script Web App มันจะไม่เหมือนเว็บโฮสต์ทั่วไปที่เราสามารถตั้งค่า 404 page อัตโนมัติในเซิร์ฟเวอร์ได้ เพราะ GAS จะรันตามโค้ดใน
doGet(e)
ของเราเท่านั้น
ดังนั้นถ้าอยากทำ 404 Page Not Found ใน Web App เราต้อง ตรวจสอบเอง ว่า request เข้ามาด้วยพารามิเตอร์ไหน และถ้าไม่เจอหน้าที่ต้องการ ให้เราส่งหน้า 404 ออกไปเอง
ตัวอย่างโครงสร้างทำ 404 ใน GAS:
code.gs
function doGet(e) { var page = e && e.parameter && e.parameter.page ? e.parameter.page : "index"; var validPages = ["index", "about", "contact"]; if (validPages.includes(page)) { return HtmlService.createTemplateFromFile(page).evaluate() .setTitle("My Web App"); } else { return HtmlService.createHtmlOutputFromFile("404") .setTitle("404 Page Not Found"); } }
404.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>404 - Page Not Found</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"> </head> <body class="text-center p-5"> <h1 class="display-3 text-danger">404</h1> <p class="lead">ขออภัย ไม่พบหน้าที่คุณค้นหา</p> <a href="?page=index" class="btn btn-primary">กลับหน้าแรก</a> </body> </html>