文件
一個 專案

handle_errors

設定錯誤處理程式。

當正常的 HTTP 要求處理程式傳回錯誤時,正常的處理會停止,並呼叫錯誤處理程式。錯誤處理程式形成一個路由,就像正常的路由一樣,它們可以執行正常的路由可以執行的任何動作。這可以在處理 HTTP 要求期間提供極佳的控制和彈性。例如,您可以提供靜態錯誤頁面、範本錯誤頁面,或反向代理到另一個後端來處理錯誤。

要求的內容會傳遞到錯誤路由中,因此在要求內容中設定的任何值,例如 網站根目錄變數,也會保留在錯誤處理程式中。此外,在處理錯誤時,可以使用 新的佔位符

請注意,某些指令,例如 reverse_proxy,可能會寫入 HTTP 狀態為錯誤分類的回應,不會 觸發錯誤路由。

您可以使用 error 指令,根據您自己的路由決策明確觸發錯誤。

語法

handle_errors {
	<directives...>
}
  • <指令...> 是 HTTP 處理器 指令比對器 的清單,每一行一個。

佔位符

處理錯誤時可以使用下列佔位符。它們是 Caddyfile 縮寫,用於 HTTP 伺服器錯誤路由的 JSON 文件 中可以找到的完整佔位符。

佔位符 說明
{err.status_code} 建議的 HTTP 狀態碼
{err.status_text} 與建議狀態碼相關聯的狀態文字
{err.message} 錯誤訊息
{err.trace} 錯誤的來源
{err.id} 此錯誤發生事件的識別碼

範例

根據狀態碼自訂錯誤頁面(例如,404 錯誤的頁面稱為 404.html)。請注意,在 handle_errors 中執行時,file_server 會保留錯誤的 HTTP 狀態碼(假設您事先在網站中設定 網站根目錄

handle_errors {
	rewrite * /{err.status_code}.html
	file_server
}

使用 templates 編寫自訂錯誤訊息的單一錯誤頁面

handle_errors {
	rewrite * /error.html
	templates
	file_server
}

如果您只想針對某些錯誤碼提供自訂錯誤頁面,可以使用 file 比對器事先檢查自訂錯誤檔案是否存在

handle_errors {
	@custom_err file /err-{err.status_code}.html /err.html
	handle @custom_err {
		rewrite * {file_match.relative}
		file_server
	}
	respond "{err.status_code} {err.status_text}"
}

反向代理到專業伺服器,該伺服器非常適合處理 HTTP 錯誤並改善您的生活 😸

handle_errors {
	rewrite * /{err.status_code}
	reverse_proxy https://http.cat {
		header_up Host {upstream_hostport}
		replace_status {err.status_code}
	}
}

只需使用 respond 回傳錯誤碼和名稱

handle_errors {
	respond "{err.status_code} {err.status_text}"
}

若要針對特定錯誤碼進行不同的處理,請使用 expression 比對器,並使用 handle 進行互斥

handle_errors {
	@404-410 `{err.status_code} in [404, 410]`
	handle @404-410 {
		respond "It's a 404 or 410 error!"
	}

	@5xx `{err.status_code} >= 500 && {err.status_code} < 600`
	handle @5xx {
		respond "It's a 5xx error."
	}

	handle {
		respond "It's another error"
	}
}