errors.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright Joyent, Inc.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package main
  7. //lint:file-ignore U1000 WIP
  8. import (
  9. "encoding/json"
  10. "fmt"
  11. "os"
  12. "reflect"
  13. "runtime/debug"
  14. "github.com/davecgh/go-spew/spew"
  15. )
  16. func errorHandler() {
  17. if r := recover(); r != nil {
  18. if API.DevelMode {
  19. if reflect.TypeOf(r).String() == "*main.ConchResponse" {
  20. res := r.(*ConchResponse)
  21. fmt.Fprintf(os.Stderr,
  22. "HTTP Status Code: %d\nHTTP Status: %s\nString Error: %s\n\n",
  23. res.StatusCode(),
  24. res.Status(),
  25. res.Error.Error(),
  26. )
  27. fmt.Fprintf(
  28. os.Stderr,
  29. "RAW HTTP RESPONSE:\n%s\n\n",
  30. res.Body,
  31. )
  32. var s interface{}
  33. if err := json.Unmarshal([]byte(res.Body), &s); err == nil {
  34. fmt.Fprintln(os.Stderr, "MARSHALLED RESPONSE:")
  35. spew.Fdump(os.Stderr, s)
  36. }
  37. } else {
  38. fmt.Fprintf(os.Stderr, "ERROR: %v\n\n", r)
  39. fmt.Fprintf(os.Stderr, "RAW ERROR: ")
  40. spew.Fdump(os.Stderr, r)
  41. }
  42. fmt.Fprintln(os.Stderr)
  43. debug.PrintStack()
  44. os.Exit(1)
  45. }
  46. var msg string
  47. if reflect.TypeOf(r).String() == "*main.ConchResponse" {
  48. res := r.(*ConchResponse)
  49. if res.Error != nil {
  50. msg = res.Error.Error()
  51. } else {
  52. msg = fmt.Sprintf("An HTTP error occured: %s", res.Status())
  53. }
  54. } else {
  55. msg = fmt.Sprintf("An error occurred: %s", r)
  56. }
  57. if API.JsonOnly {
  58. fmt.Fprintf(os.Stderr, "{\"error\":\"%s\"}\n", msg)
  59. } else {
  60. fmt.Fprintln(os.Stderr, msg)
  61. }
  62. os.Exit(1)
  63. }
  64. }
  65. func Spew(d interface{}) {
  66. spew.Fdump(os.Stderr, d)
  67. }
  68. func init() {
  69. spew.Config = spew.ConfigState{
  70. Indent: " ",
  71. SortKeys: true,
  72. DisablePointerAddresses: true,
  73. DisableMethods: true,
  74. DisableCapacities: true,
  75. DisablePointerMethods: true,
  76. SpewKeys: true,
  77. }
  78. }