bud icon indicating copy to clipboard operation
bud copied to clipboard

How to return 404?

Open adamlamar opened this issue 2 years ago • 2 comments

In the show action, I'd like to return 404 if no item in the database exists with that ID.

Is there a specific error to return for the client to get a 404, both with html and json? Is there a pattern for returning an error partial?

adamlamar avatar Sep 19 '22 01:09 adamlamar

Hey @adamlamar, it's definitely not perfect right now but you can use the pull in the http.ResponseWriter as a dependency to the controller. Then write the response status directly.

So something like:

package users

func New(w http.ResponseWriter, db *pgx.DB) *Controller {
  return &Controller{w, db}
}

type Controller struct {
  w http.ResponseWriter
  db *pgx.DB
}

func (c *Controller) Index() ([]*User, error) {
  users, _ := db.Query(`...`)
  if len(users) == 0 {
    w.WriteStatus(404)
    return nil, nil
  }
}

Also,

Is there a pattern for returning an error partial?

Not yet. As part of building the documentation, I want to add support for layouts and error pages, so this should come soon.

matthewmueller avatar Sep 23 '22 19:09 matthewmueller

Gotcha, thank you! Looking forward to the layouts and error pages too.

adamlamar avatar Sep 24 '22 02:09 adamlamar