The main server, and probably only repository in this org.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB

  1. package httperr
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "git.aiterp.net/lucifer/lucifer/internal/respond"
  9. "github.com/google/uuid"
  10. )
  11. // Error is an error that can be used.
  12. type Error struct {
  13. Status int
  14. Kind string
  15. Message string
  16. }
  17. func (err Error) Error() string {
  18. return err.Kind + ": " + err.Message
  19. }
  20. // ErrLoginRequired is a common error for when a session is expected, but none is found.
  21. var ErrLoginRequired = Error{Status: 401, Kind: "login_required", Message: "You are not logged in."}
  22. // ErrAccessDenied is a common error for when a session is expected, but none is found.
  23. var ErrAccessDenied = Error{Status: 403, Kind: "access_denied", Message: "You cannot do that."}
  24. // NotFound generates a 404 error.
  25. func NotFound(model string) Error {
  26. return Error{Status: 404, Kind: "not_found", Message: model + " not found"}
  27. }
  28. // Respond responds with the error using the format in the `respond` package. If
  29. // the error is not a httperr.Error, then it'll be logged and a 500 will be returned.
  30. func Respond(w http.ResponseWriter, err error) {
  31. if httpErr, ok := err.(Error); ok {
  32. respond.Error(w, httpErr.Status, httpErr.Kind, httpErr.Message)
  33. } else {
  34. errIDStr := ""
  35. errID, err2 := uuid.NewRandom()
  36. if err2 != nil {
  37. errID, err2 = uuid.NewUUID()
  38. if err2 != nil {
  39. errIDStr = strconv.FormatInt(time.Now().UnixNano(), 36)
  40. } else {
  41. errIDStr = errID.String()
  42. }
  43. } else {
  44. errIDStr = errID.String()
  45. }
  46. log.Printf("ERROR [%s]: %s", errIDStr, err.Error())
  47. respond.Error(w, 500, "internal_error", fmt.Sprintf("Something went wrong. It has been logged with the ID %s", errIDStr))
  48. }
  49. }