Skip to content

Latest commit

 

History

History
39 lines (32 loc) · 1.45 KB

10-错误处理.md

File metadata and controls

39 lines (32 loc) · 1.45 KB

错误处理

在我们的代码里有几处地方的错误是被忽略的。这是不好的实践,因为当一个错误一旦发生,程序会出现不可预期的行为。一个更好的解决办法是处理这些错误并返回错误信息给用户。这种方式如果有些东西出现错误,服务器会功能正常的如我们想要的,并且用户能够被通知到。

首先,让我们处理renderTemplate函数中的错误:

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    t, err := template.ParseFiles(tmpl + ".html")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    err = t.Execute(w, p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

http.Error函数发送了一个特定的HTTP应答码(在此示例中是“Internal Server Error“)和错误消息。把这个放到一个单独的函数内显然已经得到了回报。

现在让我们来修复saveHandler函数:

func saveHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/save/"):]
    body := r.FormValue("body")
    p := &Page{Title: title, Body: []byte(body)}
    err := p.save()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

在p.save()的过程中发生的任何错误都将被报告给用户。