Esempio n. 1
0
func (s *suite) TestHandleErrors(c *gc.C) {
	handleErrors := jsonhttp.HandleErrors(errorToResponse)

	// Test when handler returns an error.
	handler := handleErrors(func(http.ResponseWriter, *http.Request) error {
		return errUnauth
	})
	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, new(http.Request))
	c.Assert(rec.Code, gc.Equals, http.StatusUnauthorized)
	resp := parseErrorResponse(c, rec.Body.Bytes())
	c.Assert(resp, gc.DeepEquals, &errorResponse{
		Message: errUnauth.Error(),
	})

	// Test when handler returns nil.
	handler = handleErrors(func(w http.ResponseWriter, _ *http.Request) error {
		w.WriteHeader(http.StatusCreated)
		w.Write([]byte("something"))
		return nil
	})
	rec = httptest.NewRecorder()
	handler.ServeHTTP(rec, new(http.Request))
	c.Assert(rec.Code, gc.Equals, http.StatusCreated)
	c.Assert(rec.Body.String(), gc.Equals, "something")
}
Esempio n. 2
0
func (s *suite) TestHandleErrorsWithErrorAfterWriteHeader(c *gc.C) {
	handleErrors := jsonhttp.HandleErrors(errorToResponse)
	for i, test := range handleErrorsWithErrorAfterWriteHeaderTests {
		c.Logf("test %d: %s", i, test.about)
		handler := handleErrors(func(w http.ResponseWriter, _ *http.Request) error {
			test.causeWriteHeader(w)
			return errgo.New("unexpected")
		})
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, new(http.Request))
		c.Assert(rec.Code, gc.Equals, http.StatusOK)
		c.Assert(rec.Body.String(), gc.Equals, "")
	}
}
Esempio n. 3
0
	return string(e)
}

func (e ErrorCode) ErrorCode() ErrorCode {
	return e
}

const (
	ErrBadRequest          = ErrorCode("bad request")
	ErrDischargeRequired   = ErrorCode("macaroon discharge required")
	ErrInteractionRequired = ErrorCode("interaction required")
)

var (
	handleJSON   = jsonhttp.HandleJSON(errorToResponse)
	handleErrors = jsonhttp.HandleErrors(errorToResponse)
	writeError   = jsonhttp.WriteError(errorToResponse)
)

// Error holds the type of a response from an httpbakery HTTP request,
// marshaled as JSON.
type Error struct {
	Code    ErrorCode  `json:",omitempty"`
	Message string     `json:",omitempty"`
	Info    *ErrorInfo `json:",omitempty"`
}

// ErrorInfo holds additional information provided
// by an error.
type ErrorInfo struct {
	// Macaroon may hold a macaroon that, when