Skip to content

Commit 7973935

Browse files
committed
Transform a NRE in an UnauthorizedAccessException with clearer message
First step to handle gitextensions/gitextensions#7641
1 parent 8098def commit 7973935

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

Git.hub/Client.cs

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Linq;
4+
using System.Net;
45
using System.Threading.Tasks;
56
using RestSharp;
67
using RestSharp.Authenticators;
@@ -103,7 +104,7 @@ public Repository getRepository(string username, string repositoryName)
103104
request.AddUrlSegment("name", username);
104105
request.AddUrlSegment("repo", repositoryName);
105106

106-
var repo = client.Get<Repository>(request).Data;
107+
var repo = DoRequest<Repository>(request);
107108
if (repo == null)
108109
return null;
109110

@@ -142,11 +143,9 @@ public User getCurrentUser()
142143

143144
var request = new RestRequest("/user");
144145

145-
var user = client.Get<User>(request);
146-
if (user.Data == null)
147-
throw new Exception("Bad Credentials");
146+
var user = DoRequest<User>(request, false);
148147

149-
return user.Data;
148+
return user;
150149
}
151150

152151
public async Task<User> GetUserAsync(string userName)
@@ -172,11 +171,37 @@ public List<Repository> searchRepositories(string query)
172171
var request = new RestRequest("/legacy/repos/search/{query}");
173172
request.AddUrlSegment("query", query);
174173

175-
var repos = client.Get<APIv2.RepositoryListV2>(request).Data;
174+
var repos = DoRequest<APIv2.RepositoryListV2>(request);
176175
if (repos == null || repos.Repositories == null)
177176
throw new Exception(string.Format("Could not search for {0}", query));
178177

179178
return repos.Repositories.Select(r => r.ToV3(client)).ToList();
180179
}
180+
181+
private T DoRequest<T>(IRestRequest request, bool throwOnError = true) where T : new()
182+
{
183+
var response = client.Get<T>(request);
184+
if (response.IsSuccessful)
185+
{
186+
return response.Data;
187+
}
188+
189+
if (!throwOnError)
190+
{
191+
return default;
192+
}
193+
194+
if (response.StatusCode == HttpStatusCode.Unauthorized)
195+
{
196+
if (client.Authenticator == null)
197+
{
198+
throw new UnauthorizedAccessException("Please configure a GitHub authentication token.");
199+
}
200+
201+
throw new UnauthorizedAccessException("The GitHub authentication token provided is not valid.");
202+
}
203+
204+
throw new Exception(response.StatusDescription);
205+
}
181206
}
182207
}

0 commit comments

Comments
 (0)