github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/api/uaa/error_converter.go (about)

     1  package uaa
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  )
     7  
     8  // errorWrapper is the wrapper that converts responses with 4xx and 5xx status
     9  // codes to an error.
    10  type errorWrapper struct {
    11  	connection Connection
    12  }
    13  
    14  // NewErrorWrapper returns a new error wrapper.
    15  func NewErrorWrapper() *errorWrapper {
    16  	return new(errorWrapper)
    17  }
    18  
    19  // Wrap wraps a UAA connection in this error handling wrapper.
    20  func (e *errorWrapper) Wrap(innerconnection Connection) Connection {
    21  	e.connection = innerconnection
    22  	return e
    23  }
    24  
    25  // Make converts RawHTTPStatusError, which represents responses with 4xx and
    26  // 5xx status codes, to specific errors.
    27  func (e *errorWrapper) Make(request *http.Request, passedResponse *Response) error {
    28  	err := e.connection.Make(request, passedResponse)
    29  
    30  	if rawHTTPStatusErr, ok := err.(RawHTTPStatusError); ok {
    31  		return convert(rawHTTPStatusErr)
    32  	}
    33  
    34  	return err
    35  }
    36  
    37  func convert(rawHTTPStatusErr RawHTTPStatusError) error {
    38  	// Try to unmarshal the raw http status error into a UAA error. If
    39  	// unmarshaling fails, return the raw error.
    40  	var uaaErrorResponse UAAErrorResponse
    41  	err := json.Unmarshal(rawHTTPStatusErr.RawResponse, &uaaErrorResponse)
    42  	if err != nil {
    43  		return rawHTTPStatusErr
    44  	}
    45  
    46  	switch rawHTTPStatusErr.StatusCode {
    47  	case http.StatusBadRequest: // 400
    48  		if uaaErrorResponse.Type == "invalid_scim_resource" {
    49  			return InvalidSCIMResourceError{Message: uaaErrorResponse.Description}
    50  		}
    51  		return rawHTTPStatusErr
    52  	case http.StatusUnauthorized: // 401
    53  		if uaaErrorResponse.Type == "invalid_token" {
    54  			return InvalidAuthTokenError{Message: uaaErrorResponse.Description}
    55  		}
    56  		if uaaErrorResponse.Type == "unauthorized" {
    57  			return BadCredentialsError{Message: uaaErrorResponse.Description}
    58  		}
    59  		return rawHTTPStatusErr
    60  	case http.StatusForbidden: // 403
    61  		if uaaErrorResponse.Type == "insufficient_scope" {
    62  			return InsufficientScopeError{Message: uaaErrorResponse.Description}
    63  		}
    64  		return rawHTTPStatusErr
    65  	case http.StatusConflict: // 409
    66  		return ConflictError{Message: uaaErrorResponse.Description}
    67  	default:
    68  		return rawHTTPStatusErr
    69  	}
    70  }