diff --git a/backend/cmd/api/errors.go b/backend/cmd/api/errors.go new file mode 100644 index 0000000..91d642c --- /dev/null +++ b/backend/cmd/api/errors.go @@ -0,0 +1,57 @@ +package main + +import ( + "net/http" +) + +func (app *application) internalServerError(w http.ResponseWriter, r *http.Request, err error) { + app.logger.Error("internal error", "method", r.Method, "path", r.URL.Path, "error", err.Error()) + + writeJSONError(w, http.StatusInternalServerError, "the server encountered a problem") +} + +func (app *application) forbiddenResponse(w http.ResponseWriter, r *http.Request) { + app.logger.Warn("forbidden", "method", r.Method, "path", r.URL.Path, "error") + + writeJSONError(w, http.StatusForbidden, "forbidden") +} + +func (app *application) badRequestResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logger.Warn("bad request", "method", r.Method, "path", r.URL.Path, "error", err.Error()) + + writeJSONError(w, http.StatusBadRequest, err.Error()) +} + +func (app *application) conflictResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logger.Error("conflict response", "method", r.Method, "path", r.URL.Path, "error", err.Error()) + + writeJSONError(w, http.StatusConflict, err.Error()) +} + +func (app *application) notFoundResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logger.Warn("not found error", "method", r.Method, "path", r.URL.Path, "error", err.Error()) + + writeJSONError(w, http.StatusNotFound, "not found") +} + +func (app *application) unauthorizedErrorResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logger.Warn("unauthorized error", "method", r.Method, "path", r.URL.Path, "error", err.Error()) + + writeJSONError(w, http.StatusUnauthorized, "unauthorized") +} + +func (app *application) unauthorizedBasicErrorResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logger.Warn("unauthorized basic error", "method", r.Method, "path", r.URL.Path, "error", err.Error()) + + w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) + + writeJSONError(w, http.StatusUnauthorized, "unauthorized") +} + +func (app *application) rateLimitExceededResponse(w http.ResponseWriter, r *http.Request, retryAfter string) { + app.logger.Warn("rate limit exceeded", "method", r.Method, "path", r.URL.Path) + + w.Header().Set("Retry-After", retryAfter) + + writeJSONError(w, http.StatusTooManyRequests, "rate limit exceeded, retry after: "+retryAfter) +}