A very obvious problem with our preceding code is that it does not handle a scenario wherein an invalid ID (or GUID) is requested.
As it is, a request to, say, /page/999
will just result in a blank page for the user and in the background a Couldn't get page! message, as shown in the following screenshot:
Resolving this is pretty simple by passing proper errors. Now, in the previous chapter we explored custom 404
pages and you can certainly implement one of those here, but the easiest way is to just return an HTTP status code when a post cannot be found and allow the browser to handle the presentation.
In our preceding code, we have an error handler that doesn't do much except return the issue to our log file. Let's make that more specific:
err := database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE page_guid=?", pageGUID).Scan(&thisPage.Title, &thisPage.Content, &thisPage.Date) if err != nil { http.Error(w, http.StatusText(404), http.StatusNotFound) log.Println("Couldn't get page!") }
You will see the output in the following screenshot. Again, it would be trivial to replace this with a custom 404
page, but for now we want to make sure we're addressing the invalid requests by validating them against our database:
Providing good error messages helps improve usability for both developers and other users. In addition, it can be beneficial for SEO, so it makes sense to use HTTP status codes as defined in HTTP standards.