Plan stuff. Log stuff.
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.

82 lines
1.7 KiB

4 years ago
  1. package slerrors
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/gisle/stufflog/internal/generate"
  5. "log"
  6. "net/http"
  7. "strconv"
  8. )
  9. type SLError struct {
  10. Code int `json:"code"`
  11. Text string `json:"text"`
  12. }
  13. func (err *SLError) Error() string {
  14. return "slerror: " + err.Text + " (Suggested status code: " + strconv.Itoa(err.Code) + ")"
  15. }
  16. func (err *SLError) WithText(text string) *SLError {
  17. return &SLError{Code: err.Code, Text: text}
  18. }
  19. // GinRespond responds to a gin request.
  20. func GinRespond(c *gin.Context, err error) {
  21. serr := Wrap(err)
  22. type errResponse struct {
  23. Error *SLError `json:"error"`
  24. }
  25. if serr.Code == 500 {
  26. errId := generate.ID("E", 16)
  27. log.Println("Internal Server Error", errId, "--", err.Error())
  28. c.JSON(500, errResponse{&SLError{
  29. Code: 500,
  30. Text: "Internal server error: ref " + errId,
  31. }})
  32. return
  33. }
  34. c.JSON(serr.Code, errResponse{serr})
  35. }
  36. // Wrap wraps an error
  37. func Wrap(err error) *SLError {
  38. if slerr, ok := err.(*SLError); ok {
  39. return slerr
  40. }
  41. if _, ok := err.(*strconv.NumError); ok {
  42. return &SLError{Code: http.StatusBadRequest, Text: err.Error()}
  43. }
  44. return &SLError{Code: http.StatusInternalServerError, Text: err.Error()}
  45. }
  46. func NotFound(noun string) *SLError {
  47. return &SLError{Code: http.StatusNotFound, Text: noun + " not found"}
  48. }
  49. func PreconditionFailed(message string) *SLError {
  50. return &SLError{Code: http.StatusPreconditionFailed, Text: message}
  51. }
  52. func LoginFailed() *SLError {
  53. return &SLError{Code: http.StatusForbidden, Text: "Login Failed"}
  54. }
  55. func Unauthorized() *SLError {
  56. return &SLError{Code: http.StatusUnauthorized, Text: "Unauthorized"}
  57. }
  58. func IsNotFound(err error) bool {
  59. if serr, ok := err.(*SLError); ok && serr.Code == 404 {
  60. return true
  61. }
  62. return false
  63. }