Err
適用於 resources.GetRemote 函數返回的資源,如果 HTTP 請求失敗則返回錯誤消息,否則返回 nil。
Syntax
RESOURCE.Err
Returns
resource.resourceError
resources.GetRemote 函數返回的資源上的 Err 方法在 HTTP 請求失敗時返回錯誤消息,否則返回 nil。如果您不自己處理錯誤,Hugo 將使構建失敗。
在此示例中,我們向一個不存在的域名發送 HTTP 請求:
{{ $url := "https://broken-example.org/images/a.jpg" }}
{{ with resources.GetRemote $url }}
{{ with .Err }}
{{ errorf "%s" . }}
{{ else }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ else }}
{{ errorf "Unable to get remote resource %q" $url }}
{{ end }}上面的代碼捕獲來自 HTTP 請求的錯誤,然後使構建失敗:
ERROR error calling resources.GetRemote: Get "https://broken-example.org/images/a.jpg": dial tcp: lookup broken-example.org on 127.0.0.53:53: no such host要將錯誤記錄為警告而不是錯誤:
{{ $url := "https://broken-example.org/images/a.jpg" }}
{{ with resources.GetRemote $url }}
{{ with .Err }}
{{ warnf "%s" . }}
{{ else }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ else }}
{{ errorf "Unable to get remote resource %q" $url }}
{{ end }}帶有 404 狀態碼的 HTTP 響應不是 HTTP 請求錯誤。要處理 404 狀態碼,請使用上面所示的嵌套 with-else-end 結構進行防御性編碼。