錯誤
Err
方法作用於由 resources.GetRemote
函數返回的資源,若 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 "無法取得遠端資源 %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 "無法取得遠端資源 %q" $url }}
{{ end }}