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 结构进行防御性编码。