Autostrada
Autostrada
Create a new codebase Get Autostrada Plus
Documentation Changelog Roadmap Give feedback
Login

DocumentationTraditional web application › Error handling

Error handling

Your generated codebase will contain a cmd/web/errors.go file with helper methods for managing error conditions and sending appropriate HTTP responses to the client.

The exact contents of this file will vary depending on the options you select, but it will include at least the following methods:

Method Description
reportServerError() Logs an error message at the ERROR level and – if the error notifications option is selected – sends an email alert to a designated address containing the error details. This method does not send a HTTP response itself.
serverError() Calls reportServerError(), and then sends a 500 Internal Server Error response with a generic plaintext error message to the client. If the custom error pages option is selected, it will render the custom 500 error page instead of sending the plaintext response.
notFound() Sends the client a 404 Not Found response along with a plaintext message indicating that the resource could not be found. If the custom error pages option is selected, it will render the custom 404 page instead of sending the plaintext response.
badRequest() Sends the client a 405 Bad Request response along with an arbitrary plaintext error message. If the custom error pages option is selected, it will render the custom 400 page instead of sending the plaintext response.

These helper methods are implemented on the application type, so you can call them from your handlers or middleware whenever you need to manage an error. For example, the following code uses the notFound() and serverError() methods to handle different error return values from a database query:

func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
	...

	record, err := app.db.GetRecord(123)
	if errors.Is(err, sql.ErrNoRows) {
		app.notFound(w, r)
		return
	} else if err != nil {
		app.serverError(w, r, err)
		return
	}

	fmt.Fprintln(w, record.Name)

	...
}

Important: In most cases, you should call return immediately after using these methods so that no further code in the handler is executed.

Feel free to change the contents of the cmd/web/errors.go file or add additional methods to handle other classes of error as needed.