Documentation › JSON API › Error handling
Your generated codebase will contain a cmd/api/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 JSON body that explains the server encountered a problem and could not process the request.
|
notFound() |
Sends the client a 404 Not Found response with a JSON body that explains that the resource could not be found.
|
methodNotAllowed() |
Sends the client a 405 Method Not Allowed response with a JSON body that explains that the method is not supported for the requested resource.
|
badRequest() |
Sends the client a 400 Bad Request response with a JSON body containing an arbitrary plaintext error message.
|
In all cases, the JSON body will contain an Error key and the error message. For example, the notFound() helper will return a JSON body like this:
{
"Error": "The requested resource could not be found"
}
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/api/errors.go file or add additional methods to handle other classes of error as needed.