Handle non-200 responses from SonarQube API

Instead of letting the `json.Unmarshal` fail due to 401, return a
speaking error message.

SonarQube returns error messages for different failures. They are now
processed and printed into the bot log. They might help identify some
configuration errors.

Signed-off-by: Steven Kriegler <sk.bunsenbrenner@gmail.com>
This commit is contained in:
justusbunsi 2022-06-12 17:40:31 +02:00
parent 8acf6f76df
commit cd54dade5f
No known key found for this signature in database
GPG key ID: 82B29BF2507F9F8B
3 changed files with 31 additions and 2 deletions

View file

@ -28,6 +28,7 @@ type MeasuresComponent struct {
type MeasuresResponse struct {
Component MeasuresComponent `json:"component"`
Metrics []MeasuresComponentMetric `json:"metrics"`
Errors []Error `json:"errors"`
}
func (mr *MeasuresResponse) GetRenderedMarkdownTable() string {

View file

@ -9,6 +9,7 @@ type PullRequest struct {
type PullsResponse struct {
PullRequests []PullRequest `json:"pullRequests"`
Errors []Error `json:"errors"`
}
func (r *PullsResponse) GetPullRequest(name string) *PullRequest {

View file

@ -44,6 +44,11 @@ func retrieveDataFromApi[T PullsResponse | MeasuresResponse](sdk *SonarQubeSdk,
if err != nil {
return nil, err
}
if rawResponse.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("missing or invalid API token")
}
if rawResponse.Body != nil {
defer rawResponse.Body.Close()
}
@ -60,6 +65,10 @@ func retrieveDataFromApi[T PullsResponse | MeasuresResponse](sdk *SonarQubeSdk,
return wrapper, nil
}
type Error struct {
Message string `json:"msg"`
}
type SonarQubeSdkInterface interface {
GetMeasures(string, string) (*MeasuresResponse, error)
GetPullRequestUrl(string, int64) string
@ -91,7 +100,16 @@ func (sdk *SonarQubeSdk) fetchPullRequests(project string) (*PullsResponse, erro
return nil, err
}
return retrieveDataFromApi(sdk, request, &PullsResponse{})
response, err := retrieveDataFromApi(sdk, request, &PullsResponse{})
if err != nil {
return nil, err
}
if len(response.Errors) != 0 {
return nil, fmt.Errorf("%s", response.Errors[0].Message)
}
return response, nil
}
func (sdk *SonarQubeSdk) GetPullRequest(project string, index int64) (*PullRequest, error) {
@ -116,7 +134,16 @@ func (sdk *SonarQubeSdk) GetMeasures(project string, branch string) (*MeasuresRe
return nil, err
}
return retrieveDataFromApi(sdk, request, &MeasuresResponse{})
response, err := retrieveDataFromApi(sdk, request, &MeasuresResponse{})
if err != nil {
return nil, err
}
if len(response.Errors) != 0 {
return nil, fmt.Errorf("%s", response.Errors[0].Message)
}
return response, nil
}
func (sdk *SonarQubeSdk) ComposeGiteaComment(data *CommentComposeData) (string, error) {