2929import java .io .IOException ;
3030import java .io .InputStream ;
3131import java .io .InputStreamReader ;
32+ import java .io .Serial ;
33+ import java .net .HttpURLConnection ;
3234import java .net .URI ;
3335import java .net .URL ;
3436import java .net .http .HttpClient ;
@@ -56,14 +58,18 @@ public static ExistingGist create(final String token, final Gist gist) throws Gi
5658 try {
5759 newGist = post (token , "" , gist .toString ());
5860 } catch (IOException | InterruptedException ioe ) {
59- int code = lastCode ;
60- if (code == 404 ) {
61- return null ;
61+ if (lastCode == HttpURLConnection .HTTP_NOT_FOUND ) {
62+ throw new GistException ("Gist not found" , lastCode );
6263 }
6364 throw new GistException (lastErrorMessage , lastCode );
6465 }
6566
66- return ExistingGist .fromJson (Constants .Gsons .GSON .fromJson (newGist , JsonObject .class ));
67+ final JsonObject json = Constants .Gsons .GSON .fromJson (newGist , JsonObject .class );
68+ if (lastCode == HttpURLConnection .HTTP_UNAUTHORIZED || (json .has ("message" ) && json .get ("message" ).getAsString ().equalsIgnoreCase ("bad credentials" ))) {
69+ throw new GistException ("Bad credentials" , lastCode );
70+ }
71+
72+ return ExistingGist .fromJson (json );
6773 }
6874
6975 /**
@@ -111,13 +117,14 @@ private static void assignLastCode(HttpResponse<String> response) {
111117 }
112118
113119 public static final class GistException extends Exception {
114-
120+ @ Serial
115121 private static final long serialVersionUID = -129081029829039102L ;
116122
117123 private final String error ;
118124 private final int errorCode ;
119125
120126 GistException (final String error , final int errorCode ) {
127+ super (errorCode + " - " + error );
121128 this .error = error ;
122129 this .errorCode = errorCode ;
123130 }
@@ -134,7 +141,6 @@ public String getError() {
134141 public String toString () {
135142 return "HTTP error: %s, message: %s" .formatted (errorCode , error );
136143 }
137-
138144 }
139145
140146}
0 commit comments