theplant / containers

Better structures for building web applications
1 stars 0 forks source link

add ErrHandler #19

Closed tnclong closed 7 years ago

bodhi commented 7 years ago

@JadenTeng what is this useful for? You've provided no description, and the comments are not very helpful.

tnclong commented 7 years ago

The error as last return value of all containers methods. The goal of add ErrHandler is how to deal with these errors.

Example:

type MyContainer struct{}

func (c *MyContainer) Render(r *http.Request) (html string, err error) {
    err = gorm.ErrRecordNotFound
    return
}

type DirectWriteErr struct{}

func (h *DirectWriteErr) Process(w http.ResponseWriter, r *http.Request, err error) (progress bool) {
    if err == nil {
        return true
    }

    w.WriteHeader(http.StatusInternalServerError)
    fmt.Fprintln(w, err)
    return false
}

type RedirectToHomePage struct{}

func (h *RedirectToHomePage) Process(w http.ResponseWriter, r *http.Request, err error) (progress bool) {
    if err == nil {
        return true
    }

    http.Redirect(w, r, "/", http.StatusPermanentRedirect)

    w.WriteHeader(http.StatusInternalServerError)
    fmt.Fprintln(w, err)
    return false
}