error.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package tango
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. type AbortError interface {
  7. error
  8. Code() int
  9. }
  10. type abortError struct {
  11. code int
  12. content string
  13. }
  14. func (a *abortError) Code() int {
  15. return a.code
  16. }
  17. func (a *abortError) Error() string {
  18. return fmt.Sprintf("%v", a.content)
  19. }
  20. func Abort(code int, content ...string) AbortError {
  21. if len(content) >= 1 {
  22. return &abortError{code, content[0]}
  23. }
  24. return &abortError{code, http.StatusText(code)}
  25. }
  26. func NotFound(content ...string) AbortError {
  27. return Abort(http.StatusNotFound, content...)
  28. }
  29. func NotSupported(content ...string) AbortError {
  30. return Abort(http.StatusMethodNotAllowed, content...)
  31. }
  32. func InternalServerError(content ...string) AbortError {
  33. return Abort(http.StatusInternalServerError, content...)
  34. }
  35. func Forbidden(content ...string) AbortError {
  36. return Abort(http.StatusForbidden, content...)
  37. }
  38. func Unauthorized(content ...string) AbortError {
  39. return Abort(http.StatusUnauthorized, content...)
  40. }
  41. // default errorhandler, you can use your self handler
  42. func Errors() HandlerFunc {
  43. return func(ctx *Context) {
  44. switch res := ctx.Result.(type) {
  45. case AbortError:
  46. ctx.WriteHeader(res.Code())
  47. ctx.Write([]byte(res.Error()))
  48. case error:
  49. ctx.WriteHeader(http.StatusInternalServerError)
  50. ctx.Write([]byte(res.Error()))
  51. case []byte:
  52. ctx.WriteHeader(http.StatusInternalServerError)
  53. ctx.Write(res)
  54. case string:
  55. ctx.WriteHeader(http.StatusInternalServerError)
  56. ctx.Write([]byte(res))
  57. default:
  58. ctx.WriteHeader(http.StatusInternalServerError)
  59. ctx.Write([]byte(http.StatusText(http.StatusInternalServerError)))
  60. }
  61. }
  62. }