错误处理
Syntax
RESOURCE.Err
Returns
resource.resourceError
resources.GetRemote
(/functions/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 }}