Merge "Update the gr-avatar style to always have size 20px"
diff --git a/java/com/google/gerrit/acceptance/InProcessProtocol.java b/java/com/google/gerrit/acceptance/InProcessProtocol.java
index 8a46d57..8fcc1e7 100644
--- a/java/com/google/gerrit/acceptance/InProcessProtocol.java
+++ b/java/com/google/gerrit/acceptance/InProcessProtocol.java
@@ -232,7 +232,7 @@
       try {
         perm.check(ProjectPermission.RUN_UPLOAD_PACK);
       } catch (AuthException e) {
-        throw new ServiceNotAuthorizedException();
+        throw new ServiceNotAuthorizedException(e.getMessage(), e);
       } catch (PermissionBackendException e) {
         throw new RuntimeException(e);
       }
@@ -307,7 +307,7 @@
             .project(req.project)
             .check(ProjectPermission.RUN_RECEIVE_PACK);
       } catch (AuthException e) {
-        throw new ServiceNotAuthorizedException();
+        throw new ServiceNotAuthorizedException(e.getMessage(), e);
       } catch (PermissionBackendException e) {
         throw new RuntimeException(e);
       }
diff --git a/java/com/google/gerrit/acceptance/StandaloneSiteTest.java b/java/com/google/gerrit/acceptance/StandaloneSiteTest.java
index 1d6f51f..da93610 100644
--- a/java/com/google/gerrit/acceptance/StandaloneSiteTest.java
+++ b/java/com/google/gerrit/acceptance/StandaloneSiteTest.java
@@ -220,8 +220,11 @@
     try {
       status = p.waitFor();
     } catch (InterruptedException e) {
-      throw new InterruptedIOException(
-          "interrupted waiting for: " + Joiner.on(' ').join(pb.command()));
+      InterruptedIOException iioe =
+          new InterruptedIOException(
+              "interrupted waiting for: " + Joiner.on(' ').join(pb.command()));
+      iioe.initCause(e);
+      throw iioe;
     }
 
     String result = new String(out, UTF_8);
diff --git a/java/com/google/gerrit/entities/KeyUtil.java b/java/com/google/gerrit/entities/KeyUtil.java
index d000b31..40fb757 100644
--- a/java/com/google/gerrit/entities/KeyUtil.java
+++ b/java/com/google/gerrit/entities/KeyUtil.java
@@ -97,7 +97,7 @@
         }
       }
     } catch (ArrayIndexOutOfBoundsException err) {
-      throw new IllegalArgumentException("Bad encoding: " + e);
+      throw new IllegalArgumentException("Bad encoding" + e, err);
     }
     try {
       return new String(b, 0, bPtr, "UTF-8");
diff --git a/java/com/google/gerrit/exceptions/InvalidSshKeyException.java b/java/com/google/gerrit/exceptions/InvalidSshKeyException.java
index 8baba20..dda80cf 100644
--- a/java/com/google/gerrit/exceptions/InvalidSshKeyException.java
+++ b/java/com/google/gerrit/exceptions/InvalidSshKeyException.java
@@ -23,4 +23,8 @@
   public InvalidSshKeyException() {
     super(MESSAGE);
   }
+
+  public InvalidSshKeyException(Throwable cause) {
+    super(MESSAGE, cause);
+  }
 }
diff --git a/java/com/google/gerrit/extensions/restapi/MethodNotAllowedException.java b/java/com/google/gerrit/extensions/restapi/MethodNotAllowedException.java
index 2d59f27..8422b61 100644
--- a/java/com/google/gerrit/extensions/restapi/MethodNotAllowedException.java
+++ b/java/com/google/gerrit/extensions/restapi/MethodNotAllowedException.java
@@ -22,4 +22,12 @@
   public MethodNotAllowedException(String msg) {
     super(msg);
   }
+
+  /**
+   * @param msg error text for client describing why the method is not allowed.
+   * @param cause reason for the method not being allowed.
+   */
+  public MethodNotAllowedException(String msg, Throwable cause) {
+    super(msg, cause);
+  }
 }
diff --git a/java/com/google/gerrit/extensions/restapi/NotImplementedException.java b/java/com/google/gerrit/extensions/restapi/NotImplementedException.java
index 566159d..d74986a7 100644
--- a/java/com/google/gerrit/extensions/restapi/NotImplementedException.java
+++ b/java/com/google/gerrit/extensions/restapi/NotImplementedException.java
@@ -25,4 +25,8 @@
   public NotImplementedException(String message) {
     super(message);
   }
+
+  public NotImplementedException(String message, Throwable cause) {
+    super(message, cause);
+  }
 }
diff --git a/java/com/google/gerrit/extensions/restapi/ResourceNotFoundException.java b/java/com/google/gerrit/extensions/restapi/ResourceNotFoundException.java
index 75cf713..270a040 100644
--- a/java/com/google/gerrit/extensions/restapi/ResourceNotFoundException.java
+++ b/java/com/google/gerrit/extensions/restapi/ResourceNotFoundException.java
@@ -34,6 +34,10 @@
     super("Not found: " + id.get());
   }
 
+  public ResourceNotFoundException(IdString id, Throwable cause) {
+    super("Not found: " + id.get(), cause);
+  }
+
   public ResourceNotFoundException caching(CacheControl c) {
     setCaching(c);
     return this;
diff --git a/java/com/google/gerrit/httpd/HtmlDomUtil.java b/java/com/google/gerrit/httpd/HtmlDomUtil.java
index 25ae71c..57f2664 100644
--- a/java/com/google/gerrit/httpd/HtmlDomUtil.java
+++ b/java/com/google/gerrit/httpd/HtmlDomUtil.java
@@ -131,7 +131,7 @@
     try {
       d = newBuilder().newDocument();
     } catch (ParserConfigurationException e) {
-      throw new IOException("Cannot clone document");
+      throw new IOException("Cannot clone document", e);
     }
     Node n = d.importNode(doc.getDocumentElement(), true);
     d.appendChild(n);
diff --git a/java/com/google/gerrit/httpd/ProjectOAuthFilter.java b/java/com/google/gerrit/httpd/ProjectOAuthFilter.java
index 693232f..dab36c4 100644
--- a/java/com/google/gerrit/httpd/ProjectOAuthFilter.java
+++ b/java/com/google/gerrit/httpd/ProjectOAuthFilter.java
@@ -195,7 +195,7 @@
       defaultAuthPlugin = loginProvider.getPluginName();
       defaultAuthProvider = loginProvider.getExportName();
     } catch (NoSuchElementException e) {
-      throw new ServletException("No OAuth login provider installed");
+      throw new ServletException("No OAuth login provider installed", e);
     } catch (IllegalArgumentException e) {
       // multiple providers found => do not pick any
     }
diff --git a/java/com/google/gerrit/httpd/plugins/PluginServletContext.java b/java/com/google/gerrit/httpd/plugins/PluginServletContext.java
index 6a8ef32..40083e4 100644
--- a/java/com/google/gerrit/httpd/plugins/PluginServletContext.java
+++ b/java/com/google/gerrit/httpd/plugins/PluginServletContext.java
@@ -61,9 +61,11 @@
       try {
         handler = API.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
       } catch (NoSuchMethodException e) {
-        throw new NoSuchMethodError(
+        String msg =
             String.format(
-                "%s does not implement %s", PluginServletContext.class, method.toGenericString()));
+                "%s does not implement %s", PluginServletContext.class, method.toGenericString());
+        logger.atSevere().withCause(e).log(msg);
+        throw new NoSuchMethodError(msg);
       }
       return handler.invoke(this, args);
     }
diff --git a/java/com/google/gerrit/httpd/raw/BazelBuild.java b/java/com/google/gerrit/httpd/raw/BazelBuild.java
index a13078d..7677e97 100644
--- a/java/com/google/gerrit/httpd/raw/BazelBuild.java
+++ b/java/com/google/gerrit/httpd/raw/BazelBuild.java
@@ -63,8 +63,9 @@
     try {
       status = rebuild.waitFor();
     } catch (InterruptedException e) {
-      throw new InterruptedIOException(
-          "interrupted waiting for: " + Joiner.on(' ').join(proc.command()));
+      String msg = "interrupted waiting for: " + Joiner.on(' ').join(proc.command());
+      logger.atSevere().withCause(e).log(msg);
+      throw new InterruptedIOException(msg);
     }
     if (status != 0) {
       logger.atWarning().log("build failed: %s", new String(out, UTF_8));
diff --git a/java/com/google/gerrit/httpd/restapi/RestApiServlet.java b/java/com/google/gerrit/httpd/restapi/RestApiServlet.java
index 722955c..a81a14e6 100644
--- a/java/com/google/gerrit/httpd/restapi/RestApiServlet.java
+++ b/java/com/google/gerrit/httpd/restapi/RestApiServlet.java
@@ -1182,7 +1182,7 @@
           try {
             first = json.peek();
           } catch (EOFException e) {
-            throw new BadRequestException("Expected JSON object");
+            throw new BadRequestException("Expected JSON object", e);
           }
           if (first == JsonToken.STRING) {
             return parseString(json.nextString(), type);
diff --git a/java/com/google/gerrit/lucene/QueryBuilder.java b/java/com/google/gerrit/lucene/QueryBuilder.java
index e8ef95f..7d82bf5 100644
--- a/java/com/google/gerrit/lucene/QueryBuilder.java
+++ b/java/com/google/gerrit/lucene/QueryBuilder.java
@@ -208,7 +208,7 @@
       // subclasses of OperatorPredicate.
       value = Integer.parseInt(p.getValue());
     } catch (NumberFormatException e) {
-      throw new QueryParseException("not an integer: " + p.getValue());
+      throw new QueryParseException("not an integer: " + p.getValue(), e);
     }
     return intTermQuery.get(p.getField().getName(), value);
   }
diff --git a/java/com/google/gerrit/pgm/init/BaseInit.java b/java/com/google/gerrit/pgm/init/BaseInit.java
index 7fbf2d7..62ff66a 100644
--- a/java/com/google/gerrit/pgm/init/BaseInit.java
+++ b/java/com/google/gerrit/pgm/init/BaseInit.java
@@ -332,7 +332,7 @@
       IoUtil.loadJARs(secureStoreLib);
       return new SecureStoreInitData(secureStoreLib, secureStores.get(0));
     } catch (IOException e) {
-      throw new InvalidSecureStoreException(String.format("%s is not a valid jar", secureStore));
+      throw new InvalidSecureStoreException(String.format("%s is not a valid jar", secureStore), e);
     }
   }
 
diff --git a/java/com/google/gerrit/pgm/init/InitHttpd.java b/java/com/google/gerrit/pgm/init/InitHttpd.java
index 027a3ac..b9fe874 100644
--- a/java/com/google/gerrit/pgm/init/InitHttpd.java
+++ b/java/com/google/gerrit/pgm/init/InitHttpd.java
@@ -169,7 +169,7 @@
         uri = new URI(s + "://" + uri.getHost() + uri.getPath());
       }
     } catch (URISyntaxException e) {
-      throw die("invalid httpd.listenUrl");
+      throw die("invalid httpd.listenUrl", e);
     }
     httpd.set("listenUrl", urlbuf.toString());
     gerrit.string("Canonical URL", "canonicalWebUrl", uri.toString());
diff --git a/java/com/google/gerrit/server/ApprovalsUtil.java b/java/com/google/gerrit/server/ApprovalsUtil.java
index 29a5748..58b601f 100644
--- a/java/com/google/gerrit/server/ApprovalsUtil.java
+++ b/java/com/google/gerrit/server/ApprovalsUtil.java
@@ -331,7 +331,7 @@
         forChange.check(new LabelPermission.WithValue(name, value));
       } catch (AuthException e) {
         throw new AuthException(
-            String.format("applying label \"%s\": %d is restricted", name, value));
+            String.format("applying label \"%s\": %d is restricted", name, value), e);
       }
     }
   }
diff --git a/java/com/google/gerrit/server/account/AccountManager.java b/java/com/google/gerrit/server/account/AccountManager.java
index 8137b92..6a16a53 100644
--- a/java/com/google/gerrit/server/account/AccountManager.java
+++ b/java/com/google/gerrit/server/account/AccountManager.java
@@ -391,7 +391,7 @@
     try {
       groupsUpdate.updateGroup(groupUuid, groupUpdate);
     } catch (NoSuchGroupException e) {
-      throw new AccountException(String.format("Group %s not found", groupUuid));
+      throw new AccountException(String.format("Group %s not found", groupUuid), e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/account/externalids/ExternalId.java b/java/com/google/gerrit/server/account/externalids/ExternalId.java
index b18b27b..2d501ad 100644
--- a/java/com/google/gerrit/server/account/externalids/ExternalId.java
+++ b/java/com/google/gerrit/server/account/externalids/ExternalId.java
@@ -24,6 +24,7 @@
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
+import com.google.common.flogger.FluentLogger;
 import com.google.common.hash.Hashing;
 import com.google.gerrit.common.Nullable;
 import com.google.gerrit.entities.Account;
@@ -43,6 +44,8 @@
 
 @AutoValue
 public abstract class ExternalId implements Serializable {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
   // If these regular expressions are modified the same modifications should be done to the
   // corresponding regular expressions in the
   // com.google.gerrit.client.account.UsernameField class.
@@ -391,11 +394,12 @@
       }
       return accountId;
     } catch (IllegalArgumentException e) {
-      throw invalidConfig(
-          noteId,
+      String msg =
           String.format(
               "Value %s for '%s.%s.%s' is invalid, expected account ID",
-              accountIdStr, EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY));
+              accountIdStr, EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY);
+      logger.atSevere().withCause(e).log(msg);
+      throw invalidConfig(noteId, msg);
     }
   }
 
diff --git a/java/com/google/gerrit/server/args4j/AccountIdHandler.java b/java/com/google/gerrit/server/args4j/AccountIdHandler.java
index 4d0af53..73a970b 100644
--- a/java/com/google/gerrit/server/args4j/AccountIdHandler.java
+++ b/java/com/google/gerrit/server/args4j/AccountIdHandler.java
@@ -16,6 +16,7 @@
 
 import static com.google.gerrit.util.cli.Localizable.localizable;
 
+import com.google.common.flogger.FluentLogger;
 import com.google.gerrit.entities.Account;
 import com.google.gerrit.exceptions.StorageException;
 import com.google.gerrit.extensions.client.AuthType;
@@ -38,6 +39,8 @@
 import org.kohsuke.args4j.spi.Setter;
 
 public class AccountIdHandler extends OptionHandler<Account.Id> {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
   private final AccountResolver accountResolver;
   private final AccountManager accountManager;
   private final AuthType authType;
@@ -78,11 +81,15 @@
           case OPENID:
           case OPENID_SSO:
           default:
-            throw new CmdLineException(owner, localizable("user \"%s\" not found"), token);
+            String msg = "user \"%s\" not found";
+            logger.atSevere().withCause(e).log(msg, token);
+            throw new CmdLineException(owner, localizable(msg), token);
         }
       }
     } catch (StorageException e) {
-      throw new CmdLineException(owner, localizable("database is down"));
+      String msg = "database is down";
+      logger.atSevere().withCause(e).log(msg);
+      throw new CmdLineException(owner, localizable(msg));
     } catch (IOException e) {
       throw new CmdLineException(owner, "Failed to load account", e);
     } catch (ConfigInvalidException e) {
@@ -102,7 +109,9 @@
       req.setSkipAuthentication(true);
       return accountManager.authenticate(req).getAccountId();
     } catch (AccountException e) {
-      throw new CmdLineException(owner, localizable("user \"%s\" not found"), user);
+      String msg = "user \"%s\" not found";
+      logger.atSevere().withCause(e).log(msg, user);
+      throw new CmdLineException(owner, localizable(msg), user);
     }
   }
 
diff --git a/java/com/google/gerrit/server/args4j/ChangeIdHandler.java b/java/com/google/gerrit/server/args4j/ChangeIdHandler.java
index 9c14aca..ddcd4db 100644
--- a/java/com/google/gerrit/server/args4j/ChangeIdHandler.java
+++ b/java/com/google/gerrit/server/args4j/ChangeIdHandler.java
@@ -66,7 +66,7 @@
         return 1;
       }
     } catch (IllegalArgumentException e) {
-      throw new CmdLineException(owner, localizable("Change-Id is not valid"));
+      throw new CmdLineException(owner, localizable("Change-Id is not valid: %s"), e.getMessage());
     } catch (StorageException e) {
       throw new CmdLineException(owner, localizable("Database error: %s"), e.getMessage());
     }
diff --git a/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java b/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java
index 5016363..8b7cbd6 100644
--- a/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java
+++ b/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java
@@ -43,7 +43,8 @@
     try {
       id = PatchSet.Id.parse(token);
     } catch (IllegalArgumentException e) {
-      throw new CmdLineException(owner, localizable("\"%s\" is not a valid patch set"), token);
+      throw new CmdLineException(
+          owner, localizable("\"%s\" is not a valid patch set: %s"), token, e.getMessage());
     }
 
     setter.addValue(id);
diff --git a/java/com/google/gerrit/server/args4j/ProjectHandler.java b/java/com/google/gerrit/server/args4j/ProjectHandler.java
index abb6a1f..61dbd2c 100644
--- a/java/com/google/gerrit/server/args4j/ProjectHandler.java
+++ b/java/com/google/gerrit/server/args4j/ProjectHandler.java
@@ -89,7 +89,7 @@
       permissionBackend.currentUser().project(nameKey).check(permissionToCheck);
     } catch (AuthException e) {
       throw new CmdLineException(
-          owner, localizable(new NoSuchProjectException(nameKey).getMessage()));
+          owner, localizable(new NoSuchProjectException(nameKey, e).getMessage()));
     } catch (PermissionBackendException | IOException e) {
       logger.atWarning().withCause(e).log("Cannot load project %s", nameWithoutSuffix);
       throw new CmdLineException(
diff --git a/java/com/google/gerrit/server/cache/serialize/IntegerCacheSerializer.java b/java/com/google/gerrit/server/cache/serialize/IntegerCacheSerializer.java
index 4494454..aca9b05 100644
--- a/java/com/google/gerrit/server/cache/serialize/IntegerCacheSerializer.java
+++ b/java/com/google/gerrit/server/cache/serialize/IntegerCacheSerializer.java
@@ -37,7 +37,7 @@
       cout.writeInt32NoTag(requireNonNull(object));
       cout.flush();
     } catch (IOException e) {
-      throw new IllegalStateException("Failed to serialize int");
+      throw new IllegalStateException("Failed to serialize int", e);
     }
     int n = cout.getTotalBytesWritten();
     return n == buf.length ? buf : Arrays.copyOfRange(buf, 0, n);
@@ -50,7 +50,7 @@
     try {
       ret = cin.readRawVarint32();
     } catch (IOException e) {
-      throw new IllegalArgumentException("Failed to deserialize int");
+      throw new IllegalArgumentException("Failed to deserialize int", e);
     }
     int n = cin.getTotalBytesRead();
     if (n != in.length) {
diff --git a/java/com/google/gerrit/server/change/PureRevert.java b/java/com/google/gerrit/server/change/PureRevert.java
index f66d9bc..cb632dc 100644
--- a/java/com/google/gerrit/server/change/PureRevert.java
+++ b/java/com/google/gerrit/server/change/PureRevert.java
@@ -50,7 +50,7 @@
     try {
       claimedOriginalObjectId = ObjectId.fromString(claimedOriginal.get());
     } catch (InvalidObjectIdException e) {
-      throw new BadRequestException("invalid object ID");
+      throw new BadRequestException("invalid object ID", e);
     }
 
     return pureRevertCache.isPureRevert(
diff --git a/java/com/google/gerrit/server/config/ConfigUtil.java b/java/com/google/gerrit/server/config/ConfigUtil.java
index f476adf..43c05e0 100644
--- a/java/com/google/gerrit/server/config/ConfigUtil.java
+++ b/java/com/google/gerrit/server/config/ConfigUtil.java
@@ -30,7 +30,6 @@
 import org.eclipse.jgit.lib.Config;
 
 public class ConfigUtil {
-
   @SuppressWarnings("unchecked")
   private static <T> T[] allValuesOf(T defaultValue) {
     try {
@@ -182,7 +181,7 @@
     try {
       return getTimeUnit(s, defaultValue, wantUnit);
     } catch (IllegalArgumentException notTime) {
-      throw notTimeUnit(section, subsection, setting, valueString);
+      throw notTimeUnit(section, subsection, setting, valueString, notTime);
     }
   }
 
@@ -250,7 +249,7 @@
     try {
       return wantUnit.convert(Long.parseLong(digits) * inputMul, inputUnit);
     } catch (NumberFormatException nfe) {
-      throw notTimeUnit(valueString);
+      throw notTimeUnit(valueString, nfe);
     }
   }
 
@@ -421,13 +420,21 @@
   }
 
   private static IllegalArgumentException notTimeUnit(
-      final String section,
-      final String subsection,
-      final String setting,
-      final String valueString) {
-    return new IllegalArgumentException(
-        "Invalid time unit value: "
-            + section
+      String section, String subsection, String setting, String valueString, Throwable why) {
+    return notTimeUnit(
+        section
+            + (subsection != null ? "." + subsection : "")
+            + "."
+            + setting
+            + " = "
+            + valueString,
+        why);
+  }
+
+  private static IllegalArgumentException notTimeUnit(
+      String section, String subsection, String setting, String valueString) {
+    return notTimeUnit(
+        section
             + (subsection != null ? "." + subsection : "")
             + "."
             + setting
@@ -439,5 +446,9 @@
     return new IllegalArgumentException("Invalid time unit value: " + val);
   }
 
+  private static IllegalArgumentException notTimeUnit(String val, Throwable why) {
+    return new IllegalArgumentException("Invalid time unit value: " + val, why);
+  }
+
   private ConfigUtil() {}
 }
diff --git a/java/com/google/gerrit/server/git/MergeUtil.java b/java/com/google/gerrit/server/git/MergeUtil.java
index 1dbf029..801300e 100644
--- a/java/com/google/gerrit/server/git/MergeUtil.java
+++ b/java/com/google/gerrit/server/git/MergeUtil.java
@@ -760,6 +760,7 @@
       try {
         failed(rw, mergeTip, n, getCommitMergeStatus(e.getReason()));
       } catch (IOException e2) {
+        logger.atSevere().withCause(e2).log("Failed to set merge failure status for " + n.name());
         throw new IntegrationException("Cannot merge " + n.name(), e);
       }
     } catch (IOException e) {
diff --git a/java/com/google/gerrit/server/git/PermissionAwareReadOnlyRefDatabase.java b/java/com/google/gerrit/server/git/PermissionAwareReadOnlyRefDatabase.java
index 1bd8b45..b7dc2b3 100644
--- a/java/com/google/gerrit/server/git/PermissionAwareReadOnlyRefDatabase.java
+++ b/java/com/google/gerrit/server/git/PermissionAwareReadOnlyRefDatabase.java
@@ -106,7 +106,7 @@
     try {
       result = forProject.filter(refs, getDelegate(), RefFilterOptions.defaults());
     } catch (PermissionBackendException e) {
-      throw new IOException("");
+      throw new IOException("", e);
     }
     return buildPrefixRefMap(prefix, result);
   }
diff --git a/java/com/google/gerrit/server/git/PureRevertCache.java b/java/com/google/gerrit/server/git/PureRevertCache.java
index b21cb5c..9f9530c 100644
--- a/java/com/google/gerrit/server/git/PureRevertCache.java
+++ b/java/com/google/gerrit/server/git/PureRevertCache.java
@@ -166,7 +166,7 @@
           try {
             claimedOriginalCommit = rw.parseCommit(original);
           } catch (InvalidObjectIdException | MissingObjectException e) {
-            throw new BadRequestException("invalid object ID");
+            throw new BadRequestException("invalid object ID", e);
           }
           if (claimedOriginalCommit.getParentCount() == 0) {
             throw new BadRequestException("can't check against initial commit");
diff --git a/java/com/google/gerrit/server/git/validators/CommitValidationException.java b/java/com/google/gerrit/server/git/validators/CommitValidationException.java
index 4dd2951..220fc12 100644
--- a/java/com/google/gerrit/server/git/validators/CommitValidationException.java
+++ b/java/com/google/gerrit/server/git/validators/CommitValidationException.java
@@ -32,6 +32,11 @@
     this.messages = ImmutableList.of(message);
   }
 
+  public CommitValidationException(String reason, CommitValidationMessage message, Throwable why) {
+    super(reason, why);
+    this.messages = ImmutableList.of(message);
+  }
+
   public CommitValidationException(String reason, List<CommitValidationMessage> messages) {
     super(reason);
     this.messages = ImmutableList.copyOf(messages);
diff --git a/java/com/google/gerrit/server/git/validators/CommitValidators.java b/java/com/google/gerrit/server/git/validators/CommitValidators.java
index 4159ebb..160248c 100644
--- a/java/com/google/gerrit/server/git/validators/CommitValidators.java
+++ b/java/com/google/gerrit/server/git/validators/CommitValidators.java
@@ -500,7 +500,7 @@
         perm.check(RefPermission.MERGE);
         return Collections.emptyList();
       } catch (AuthException e) {
-        throw new CommitValidationException("you are not allowed to upload merges");
+        throw new CommitValidationException("you are not allowed to upload merges", e);
       } catch (PermissionBackendException e) {
         logger.atSevere().withCause(e).log("cannot check MERGE");
         throw new CommitValidationException("internal auth error");
@@ -597,7 +597,7 @@
           perm.check(RefPermission.FORGE_COMMITTER);
         } catch (AuthException denied) {
           throw new CommitValidationException(
-              "not Signed-off-by author/committer/uploader in message footer");
+              "not Signed-off-by author/committer/uploader in message footer", denied);
         } catch (PermissionBackendException e) {
           logger.atSevere().withCause(e).log("cannot check FORGE_COMMITTER");
           throw new CommitValidationException("internal auth error");
@@ -632,7 +632,7 @@
         return Collections.emptyList();
       } catch (AuthException e) {
         throw new CommitValidationException(
-            "invalid author", invalidEmail("author", author, user, urlFormatter));
+            "invalid author", invalidEmail("author", author, user, urlFormatter), e);
       } catch (PermissionBackendException e) {
         logger.atSevere().withCause(e).log("cannot check FORGE_AUTHOR");
         throw new CommitValidationException("internal auth error");
@@ -665,7 +665,7 @@
         return Collections.emptyList();
       } catch (AuthException e) {
         throw new CommitValidationException(
-            "invalid committer", invalidEmail("committer", committer, user, urlFormatter));
+            "invalid committer", invalidEmail("committer", committer, user, urlFormatter), e);
       } catch (PermissionBackendException e) {
         logger.atSevere().withCause(e).log("cannot check FORGE_COMMITTER");
         throw new CommitValidationException("internal auth error");
@@ -704,7 +704,8 @@
                   "pushing merge commit %s by %s requires '%s' permission",
                   receiveEvent.commit.getId(),
                   gerritIdent.getEmailAddress(),
-                  RefPermission.FORGE_SERVER.name()));
+                  RefPermission.FORGE_SERVER.name()),
+              denied);
         } catch (PermissionBackendException e) {
           logger.atSevere().withCause(e).log("cannot check FORGE_SERVER");
           throw new CommitValidationException("internal auth error");
diff --git a/java/com/google/gerrit/server/git/validators/MergeValidationException.java b/java/com/google/gerrit/server/git/validators/MergeValidationException.java
index 3624fe0..2b7803d 100644
--- a/java/com/google/gerrit/server/git/validators/MergeValidationException.java
+++ b/java/com/google/gerrit/server/git/validators/MergeValidationException.java
@@ -28,4 +28,8 @@
   public MergeValidationException(String msg) {
     super(msg);
   }
+
+  public MergeValidationException(String msg, Throwable why) {
+    super(msg, why);
+  }
 }
diff --git a/java/com/google/gerrit/server/git/validators/MergeValidators.java b/java/com/google/gerrit/server/git/validators/MergeValidators.java
index 8abe5c6..9c557a7 100644
--- a/java/com/google/gerrit/server/git/validators/MergeValidators.java
+++ b/java/com/google/gerrit/server/git/validators/MergeValidators.java
@@ -192,7 +192,7 @@
                 try {
                   permissionBackend.user(caller).check(GlobalPermission.ADMINISTRATE_SERVER);
                 } catch (AuthException e) {
-                  throw new MergeValidationException(SET_BY_ADMIN);
+                  throw new MergeValidationException(SET_BY_ADMIN, e);
                 } catch (PermissionBackendException e) {
                   logger.atWarning().withCause(e).log("Cannot check ADMINISTRATE_SERVER");
                   throw new MergeValidationException("validation unavailable");
@@ -204,7 +204,7 @@
                       .project(destProject.getNameKey())
                       .check(ProjectPermission.WRITE_CONFIG);
                 } catch (AuthException e) {
-                  throw new MergeValidationException(SET_BY_OWNER);
+                  throw new MergeValidationException(SET_BY_OWNER, e);
                 } catch (PermissionBackendException e) {
                   logger.atWarning().withCause(e).log("Cannot check WRITE_CONFIG");
                   throw new MergeValidationException("validation unavailable");
@@ -245,7 +245,7 @@
             }
           }
         } catch (ConfigInvalidException | IOException e) {
-          throw new MergeValidationException(INVALID_CONFIG);
+          throw new MergeValidationException(INVALID_CONFIG, e);
         }
       }
     }
diff --git a/java/com/google/gerrit/server/git/validators/RefOperationValidators.java b/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
index f3d8f4a..f3b6983 100644
--- a/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
+++ b/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
@@ -134,7 +134,7 @@
             try {
               perm.check(GlobalPermission.ACCESS_DATABASE);
             } catch (AuthException | PermissionBackendException e) {
-              throw new ValidationException("Not allowed to create user branch.");
+              throw new ValidationException("Not allowed to create user branch.", e);
             }
             if (Account.Id.fromRef(refEvent.command.getRefName()) == null) {
               throw new ValidationException(
@@ -145,7 +145,7 @@
             try {
               perm.check(GlobalPermission.ACCESS_DATABASE);
             } catch (AuthException | PermissionBackendException e) {
-              throw new ValidationException("Not allowed to delete user branch.");
+              throw new ValidationException("Not allowed to delete user branch.", e);
             }
           }
         }
diff --git a/java/com/google/gerrit/server/mail/send/ChangeEmail.java b/java/com/google/gerrit/server/mail/send/ChangeEmail.java
index d7f09d2..9e53c65 100644
--- a/java/com/google/gerrit/server/mail/send/ChangeEmail.java
+++ b/java/com/google/gerrit/server/mail/send/ChangeEmail.java
@@ -293,7 +293,7 @@
       try {
         ps = args.patchSetUtil.get(changeData.notes(), PatchSet.id(change.getId(), patchSetId));
       } catch (StorageException e) {
-        throw new PatchListNotAvailableException("Failed to get patchSet");
+        throw new PatchListNotAvailableException("Failed to get patchSet", e);
       }
     }
     return args.patchListCache.get(change, ps);
diff --git a/java/com/google/gerrit/server/notedb/ChangeNotesParser.java b/java/com/google/gerrit/server/notedb/ChangeNotesParser.java
index 5468e23..428df16 100644
--- a/java/com/google/gerrit/server/notedb/ChangeNotesParser.java
+++ b/java/com/google/gerrit/server/notedb/ChangeNotesParser.java
@@ -907,7 +907,9 @@
     try {
       adr = Address.parse(line);
     } catch (IllegalArgumentException e) {
-      throw invalidFooter(state.getByEmailFooterKey(), line);
+      ConfigInvalidException cie = invalidFooter(state.getByEmailFooterKey(), line);
+      cie.initCause(e);
+      throw cie;
     }
     if (!reviewersByEmail.containsRow(adr)) {
       reviewersByEmail.put(adr, state, ts);
diff --git a/java/com/google/gerrit/server/patch/PatchScriptFactory.java b/java/com/google/gerrit/server/patch/PatchScriptFactory.java
index afc1ab1..b7b3d81 100644
--- a/java/com/google/gerrit/server/patch/PatchScriptFactory.java
+++ b/java/com/google/gerrit/server/patch/PatchScriptFactory.java
@@ -193,7 +193,7 @@
     try {
       permissionBackend.currentUser().change(notes).check(ChangePermission.READ);
     } catch (AuthException e) {
-      throw new NoSuchChangeException(changeId);
+      throw new NoSuchChangeException(changeId, e);
     }
 
     if (!projectCache.checkedGet(notes.getProjectName()).statePermitsRead()) {
diff --git a/java/com/google/gerrit/server/patch/PatchScriptFactoryForAutoFix.java b/java/com/google/gerrit/server/patch/PatchScriptFactoryForAutoFix.java
index cf07190..2e39607 100644
--- a/java/com/google/gerrit/server/patch/PatchScriptFactoryForAutoFix.java
+++ b/java/com/google/gerrit/server/patch/PatchScriptFactoryForAutoFix.java
@@ -98,7 +98,7 @@
     try {
       permissionBackend.currentUser().change(notes).check(ChangePermission.READ);
     } catch (AuthException e) {
-      throw new NoSuchChangeException(changeId);
+      throw new NoSuchChangeException(changeId, e);
     }
 
     if (!projectCache.checkedGet(notes.getProjectName()).statePermitsRead()) {
diff --git a/java/com/google/gerrit/server/project/ProjectCreator.java b/java/com/google/gerrit/server/project/ProjectCreator.java
index ba44142..c4c466e 100644
--- a/java/com/google/gerrit/server/project/ProjectCreator.java
+++ b/java/com/google/gerrit/server/project/ProjectCreator.java
@@ -132,9 +132,10 @@
               + nameKey.get()
               + " because the name is already occupied by another project."
               + " The other project has the same name, only spelled in a"
-              + " different case.");
+              + " different case.",
+          e);
     } catch (RepositoryNotFoundException badName) {
-      throw new BadRequestException("invalid project name: " + nameKey);
+      throw new BadRequestException("invalid project name: " + nameKey, badName);
     } catch (ConfigInvalidException e) {
       String msg = "Cannot create " + nameKey;
       logger.atSevere().withCause(e).log(msg);
diff --git a/java/com/google/gerrit/server/project/RefUtil.java b/java/com/google/gerrit/server/project/RefUtil.java
index 5d6379a..dc8cdc7 100644
--- a/java/com/google/gerrit/server/project/RefUtil.java
+++ b/java/com/google/gerrit/server/project/RefUtil.java
@@ -55,7 +55,7 @@
           "Cannot resolve \"%s\" in project \"%s\"", baseRevision, projectName.get());
       throw new InvalidRevisionException(baseRevision);
     } catch (RevisionSyntaxException err) {
-      throw new InvalidRevisionException(baseRevision);
+      throw new InvalidRevisionException(baseRevision, err);
     }
   }
 
@@ -66,7 +66,7 @@
       try {
         rw.markStart(rw.parseCommit(revid));
       } catch (IncorrectObjectTypeException err) {
-        throw new InvalidRevisionException(revid.name());
+        throw new InvalidRevisionException(revid.name(), err);
       }
       RefDatabase refDb = repo.getRefDatabase();
       Iterable<Ref> refs =
@@ -86,7 +86,7 @@
       rw.checkConnectivity();
       return rw;
     } catch (IncorrectObjectTypeException | MissingObjectException err) {
-      throw new InvalidRevisionException(revid.name());
+      throw new InvalidRevisionException(revid.name(), err);
     } catch (IOException err) {
       logger.atSevere().withCause(err).log(
           "Repository \"%s\" may be corrupt; suggest running git fsck", repo.getDirectory());
@@ -128,5 +128,9 @@
     InvalidRevisionException(@Nullable String invalidRevision) {
       super(MESSAGE + ": " + invalidRevision);
     }
+
+    InvalidRevisionException(@Nullable String invalidRevision, Throwable why) {
+      super(MESSAGE + ": " + invalidRevision, why);
+    }
   }
 }
diff --git a/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java b/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java
index 664df70..42a8310 100644
--- a/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java
+++ b/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java
@@ -123,7 +123,9 @@
     try {
       args.permissionBackend.user(args.getUser()).change(changeNotes).check(ChangePermission.READ);
     } catch (AuthException e) {
-      throw error(String.format("change %s not found", change));
+      String msg = String.format("change %s not found", change);
+      logger.atSevere().withCause(e).log(msg);
+      throw error(msg);
     }
 
     return AccountPredicates.cansee(args, changeNotes);
diff --git a/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java b/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java
index 7747998..11fb0d6 100644
--- a/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java
+++ b/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java
@@ -1288,7 +1288,8 @@
         throw new QueryParseException(
             "'"
                 + value
-                + "' is not a valid input. It must be in the 'ChangeNumber[,PatchsetNumber]' format.");
+                + "' is not a valid input. It must be in the 'ChangeNumber[,PatchsetNumber]' format.",
+            e);
       }
     }
     throw new QueryParseException(
diff --git a/java/com/google/gerrit/server/query/project/ProjectQueryBuilder.java b/java/com/google/gerrit/server/query/project/ProjectQueryBuilder.java
index 2992869..d234546 100644
--- a/java/com/google/gerrit/server/query/project/ProjectQueryBuilder.java
+++ b/java/com/google/gerrit/server/query/project/ProjectQueryBuilder.java
@@ -75,7 +75,7 @@
     try {
       parsedState = ProjectState.valueOf(state.replace('-', '_').toUpperCase());
     } catch (IllegalArgumentException e) {
-      throw error("state operator must be either 'active' or 'read-only'");
+      throw error("state operator must be either 'active' or 'read-only'", e);
     }
     if (parsedState == ProjectState.HIDDEN) {
       throw error("state operator must be either 'active' or 'read-only'");
diff --git a/java/com/google/gerrit/server/restapi/account/Capabilities.java b/java/com/google/gerrit/server/restapi/account/Capabilities.java
index 07b1214..3d719ff9 100644
--- a/java/com/google/gerrit/server/restapi/account/Capabilities.java
+++ b/java/com/google/gerrit/server/restapi/account/Capabilities.java
@@ -75,7 +75,7 @@
       permissionBackend.absentUser(target.getAccountId()).check(perm);
       return new AccountResource.Capability(target, globalOrPluginPermissionName(perm));
     } catch (AuthException e) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/account/CreateAccount.java b/java/com/google/gerrit/server/restapi/account/CreateAccount.java
index 8f525ef..907dd18 100644
--- a/java/com/google/gerrit/server/restapi/account/CreateAccount.java
+++ b/java/com/google/gerrit/server/restapi/account/CreateAccount.java
@@ -163,7 +163,7 @@
       try {
         addGroupMember(groupUuid, accountId);
       } catch (NoSuchGroupException e) {
-        throw new UnprocessableEntityException(String.format("Group %s not found", groupUuid));
+        throw new UnprocessableEntityException(String.format("Group %s not found", groupUuid), e);
       }
     }
 
diff --git a/java/com/google/gerrit/server/restapi/account/PutAgreement.java b/java/com/google/gerrit/server/restapi/account/PutAgreement.java
index 459ff26..42504a0 100644
--- a/java/com/google/gerrit/server/restapi/account/PutAgreement.java
+++ b/java/com/google/gerrit/server/restapi/account/PutAgreement.java
@@ -100,7 +100,7 @@
     try {
       addMembers.addMembers(uuid, ImmutableSet.of(accountState.account().id()));
     } catch (NoSuchGroupException e) {
-      throw new ResourceConflictException("autoverify group not found");
+      throw new ResourceConflictException("autoverify group not found", e);
     }
     agreementSignup.fire(accountState, agreementName);
 
diff --git a/java/com/google/gerrit/server/restapi/account/PutUsername.java b/java/com/google/gerrit/server/restapi/account/PutUsername.java
index dabfaa5..dc841b8 100644
--- a/java/com/google/gerrit/server/restapi/account/PutUsername.java
+++ b/java/com/google/gerrit/server/restapi/account/PutUsername.java
@@ -122,7 +122,7 @@
       }
 
       // Otherwise, someone else has this identity.
-      throw new ResourceConflictException("username already used");
+      throw new ResourceConflictException("username already used", dupeErr);
     }
 
     sshKeyCache.evict(input.username);
diff --git a/java/com/google/gerrit/server/restapi/account/SshKeys.java b/java/com/google/gerrit/server/restapi/account/SshKeys.java
index 6e3f905..a6c4d80 100644
--- a/java/com/google/gerrit/server/restapi/account/SshKeys.java
+++ b/java/com/google/gerrit/server/restapi/account/SshKeys.java
@@ -70,7 +70,7 @@
         permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
       } catch (AuthException e) {
         // If lacking MODIFY_ACCOUNT claim the resource does not exist.
-        throw new ResourceNotFoundException();
+        throw new ResourceNotFoundException(id, e);
       }
     }
     return parse(rsrc.getUser(), id);
@@ -86,7 +86,7 @@
       }
       return new AccountResource.SshKey(user, sshKey);
     } catch (NumberFormatException e) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/account/StarredChanges.java b/java/com/google/gerrit/server/restapi/account/StarredChanges.java
index 3c14ad3..c108dcb 100644
--- a/java/com/google/gerrit/server/restapi/account/StarredChanges.java
+++ b/java/com/google/gerrit/server/restapi/account/StarredChanges.java
@@ -123,10 +123,10 @@
       try {
         change = changes.parse(TopLevelResource.INSTANCE, id);
       } catch (ResourceNotFoundException e) {
-        throw new UnprocessableEntityException(String.format("change %s not found", id.get()));
+        throw new UnprocessableEntityException(String.format("change %s not found", id.get()), e);
       } catch (StorageException | PermissionBackendException | IOException e) {
         logger.atSevere().withCause(e).log("cannot resolve change");
-        throw new UnprocessableEntityException("internal server error");
+        throw new UnprocessableEntityException("internal server error", e);
       }
 
       try {
diff --git a/java/com/google/gerrit/server/restapi/change/CherryPickChange.java b/java/com/google/gerrit/server/restapi/change/CherryPickChange.java
index 3496491..ac81b45 100644
--- a/java/com/google/gerrit/server/restapi/change/CherryPickChange.java
+++ b/java/com/google/gerrit/server/restapi/change/CherryPickChange.java
@@ -422,7 +422,8 @@
     try {
       baseObjectId = ObjectId.fromString(base);
     } catch (InvalidObjectIdException e) {
-      throw new BadRequestException(String.format("Base %s doesn't represent a valid SHA-1", base));
+      throw new BadRequestException(
+          String.format("Base %s doesn't represent a valid SHA-1", base), e);
     }
 
     RevCommit baseCommit;
diff --git a/java/com/google/gerrit/server/restapi/change/CreateMergePatchSet.java b/java/com/google/gerrit/server/restapi/change/CreateMergePatchSet.java
index 8d50b86..06478ac 100644
--- a/java/com/google/gerrit/server/restapi/change/CreateMergePatchSet.java
+++ b/java/com/google/gerrit/server/restapi/change/CreateMergePatchSet.java
@@ -205,7 +205,7 @@
     try {
       permissionBackend.currentUser().change(change).check(ChangePermission.READ);
     } catch (AuthException e) {
-      throw new UnprocessableEntityException("Read not permitted for " + baseChange);
+      throw new UnprocessableEntityException("Read not permitted for " + baseChange, e);
     }
     return psUtil.current(change);
   }
diff --git a/java/com/google/gerrit/server/restapi/change/GetDiff.java b/java/com/google/gerrit/server/restapi/change/GetDiff.java
index c1d286a..c3deb79 100644
--- a/java/com/google/gerrit/server/restapi/change/GetDiff.java
+++ b/java/com/google/gerrit/server/restapi/change/GetDiff.java
@@ -293,6 +293,7 @@
             throw new NumberFormatException();
           }
         } catch (NumberFormatException e) {
+          logger.atFine().withCause(e).log("invalid numeric value");
           throw new CmdLineException(
               owner,
               localizable("\"%s\" is not a valid value for \"%s\""),
diff --git a/java/com/google/gerrit/server/restapi/change/PostReview.java b/java/com/google/gerrit/server/restapi/change/PostReview.java
index 324069d..ddb112a2 100644
--- a/java/com/google/gerrit/server/restapi/change/PostReview.java
+++ b/java/com/google/gerrit/server/restapi/change/PostReview.java
@@ -514,7 +514,8 @@
           throw new AuthException(
               String.format(
                   "not permitted to modify label \"%s\" on behalf of \"%s\"",
-                  type.getName(), in.onBehalfOf));
+                  type.getName(), in.onBehalfOf),
+              e);
         }
       }
     }
@@ -530,7 +531,7 @@
       permissionBackend.user(reviewer).change(rev.getNotes()).check(ChangePermission.READ);
     } catch (AuthException e) {
       throw new UnprocessableEntityException(
-          String.format("on_behalf_of account %s cannot see change", reviewer.getAccountId()));
+          String.format("on_behalf_of account %s cannot see change", reviewer.getAccountId()), e);
     }
 
     return new RevisionResource(
@@ -580,7 +581,7 @@
         perm.check(new LabelPermission.WithValue(lt, val));
       } catch (AuthException e) {
         throw new AuthException(
-            String.format("Applying label \"%s\": %d is restricted", lt.getName(), val));
+            String.format("Applying label \"%s\": %d is restricted", lt.getName(), val), e);
       }
     }
   }
diff --git a/java/com/google/gerrit/server/restapi/change/PreviewSubmit.java b/java/com/google/gerrit/server/restapi/change/PreviewSubmit.java
index ee1f2e3..e6a60d5 100644
--- a/java/com/google/gerrit/server/restapi/change/PreviewSubmit.java
+++ b/java/com/google/gerrit/server/restapi/change/PreviewSubmit.java
@@ -174,7 +174,7 @@
           archiveFormat.putEntry(aos, path, bos.toByteArray());
         }
       } catch (LimitExceededException e) {
-        throw new NotImplementedException("The bundle is too big to generate at the server");
+        throw new NotImplementedException("The bundle is too big to generate at the server", e);
       } catch (NoSuchProjectException e) {
         throw new IOException(e);
       }
diff --git a/java/com/google/gerrit/server/restapi/change/PutAssignee.java b/java/com/google/gerrit/server/restapi/change/PutAssignee.java
index dc1adfa..7b0d905 100644
--- a/java/com/google/gerrit/server/restapi/change/PutAssignee.java
+++ b/java/com/google/gerrit/server/restapi/change/PutAssignee.java
@@ -94,7 +94,7 @@
           .change(rsrc.getNotes())
           .check(ChangePermission.READ);
     } catch (AuthException e) {
-      throw new AuthException("read not permitted for " + input.assignee);
+      throw new AuthException("read not permitted for " + input.assignee, e);
     }
 
     try (BatchUpdate bu =
diff --git a/java/com/google/gerrit/server/restapi/change/QueryChanges.java b/java/com/google/gerrit/server/restapi/change/QueryChanges.java
index 544177f..878e714 100644
--- a/java/com/google/gerrit/server/restapi/change/QueryChanges.java
+++ b/java/com/google/gerrit/server/restapi/change/QueryChanges.java
@@ -129,7 +129,7 @@
     try {
       out = query();
     } catch (QueryRequiresAuthException e) {
-      throw new AuthException("Must be signed-in to use this operator");
+      throw new AuthException("Must be signed-in to use this operator", e);
     } catch (QueryParseException e) {
       logger.atFine().withCause(e).log("Reject change query with 400 Bad Request: %s", queries);
       throw new BadRequestException(e.getMessage(), e);
diff --git a/java/com/google/gerrit/server/restapi/change/Submit.java b/java/com/google/gerrit/server/restapi/change/Submit.java
index 53e96f7..6fc3ece 100644
--- a/java/com/google/gerrit/server/restapi/change/Submit.java
+++ b/java/com/google/gerrit/server/restapi/change/Submit.java
@@ -438,7 +438,7 @@
       permissionBackend.user(submitter).change(rsrc.getNotes()).check(ChangePermission.READ);
     } catch (AuthException e) {
       throw new UnprocessableEntityException(
-          String.format("on_behalf_of account %s cannot see change", submitter.getAccountId()));
+          String.format("on_behalf_of account %s cannot see change", submitter.getAccountId()), e);
     }
     return submitter;
   }
diff --git a/java/com/google/gerrit/server/restapi/config/ConfirmEmail.java b/java/com/google/gerrit/server/restapi/config/ConfirmEmail.java
index 03715c9..b55562e 100644
--- a/java/com/google/gerrit/server/restapi/config/ConfirmEmail.java
+++ b/java/com/google/gerrit/server/restapi/config/ConfirmEmail.java
@@ -88,7 +88,7 @@
       }
       throw new UnprocessableEntityException("invalid token");
     } catch (EmailTokenVerifier.InvalidTokenException e) {
-      throw new UnprocessableEntityException("invalid token");
+      throw new UnprocessableEntityException("invalid token", e);
     } catch (AccountException e) {
       throw new UnprocessableEntityException(e.getMessage());
     }
diff --git a/java/com/google/gerrit/server/restapi/config/TasksCollection.java b/java/com/google/gerrit/server/restapi/config/TasksCollection.java
index 289f76f..837d071 100644
--- a/java/com/google/gerrit/server/restapi/config/TasksCollection.java
+++ b/java/com/google/gerrit/server/restapi/config/TasksCollection.java
@@ -81,7 +81,7 @@
     try {
       taskId = (int) Long.parseLong(id.get(), 16);
     } catch (NumberFormatException e) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, e);
     }
 
     Task<?> task = workQueue.getTask(taskId);
diff --git a/java/com/google/gerrit/server/restapi/group/AddMembers.java b/java/com/google/gerrit/server/restapi/group/AddMembers.java
index b60d78e..93d095d 100644
--- a/java/com/google/gerrit/server/restapi/group/AddMembers.java
+++ b/java/com/google/gerrit/server/restapi/group/AddMembers.java
@@ -138,7 +138,7 @@
     try {
       addMembers(groupUuid, newMemberIds);
     } catch (NoSuchGroupException e) {
-      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
     }
     return Response.ok(toAccountInfoList(newMemberIds));
   }
@@ -234,7 +234,7 @@
         }
         throw new IllegalStateException();
       } catch (UnprocessableEntityException e) {
-        throw new ResourceNotFoundException(id);
+        throw new ResourceNotFoundException(id, e);
       }
     }
   }
diff --git a/java/com/google/gerrit/server/restapi/group/AddSubgroups.java b/java/com/google/gerrit/server/restapi/group/AddSubgroups.java
index c969ace..3fd3f29 100644
--- a/java/com/google/gerrit/server/restapi/group/AddSubgroups.java
+++ b/java/com/google/gerrit/server/restapi/group/AddSubgroups.java
@@ -116,7 +116,7 @@
     try {
       addSubgroups(groupUuid, subgroupUuids);
     } catch (NoSuchGroupException e) {
-      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
     }
     return Response.ok(result);
   }
@@ -153,7 +153,7 @@
         }
         throw new IllegalStateException();
       } catch (UnprocessableEntityException e) {
-        throw new ResourceNotFoundException(id);
+        throw new ResourceNotFoundException(id, e);
       }
     }
   }
diff --git a/java/com/google/gerrit/server/restapi/group/CreateGroup.java b/java/com/google/gerrit/server/restapi/group/CreateGroup.java
index b80b0e4..531d350 100644
--- a/java/com/google/gerrit/server/restapi/group/CreateGroup.java
+++ b/java/com/google/gerrit/server/restapi/group/CreateGroup.java
@@ -220,7 +220,7 @@
       return groupsUpdateProvider.get().createGroup(groupCreation, groupUpdateBuilder.build());
     } catch (DuplicateKeyException e) {
       throw new ResourceConflictException(
-          "group '" + createGroupArgs.getGroupName() + "' already exists");
+          "group '" + createGroupArgs.getGroupName() + "' already exists", e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/restapi/group/DeleteMembers.java b/java/com/google/gerrit/server/restapi/group/DeleteMembers.java
index fa1c5c6..a7b2e2d 100644
--- a/java/com/google/gerrit/server/restapi/group/DeleteMembers.java
+++ b/java/com/google/gerrit/server/restapi/group/DeleteMembers.java
@@ -78,7 +78,7 @@
     try {
       removeGroupMembers(groupUuid, membersToRemove);
     } catch (NoSuchGroupException e) {
-      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
     }
 
     return Response.none();
diff --git a/java/com/google/gerrit/server/restapi/group/DeleteSubgroups.java b/java/com/google/gerrit/server/restapi/group/DeleteSubgroups.java
index ef8612e..b9d6ca8 100644
--- a/java/com/google/gerrit/server/restapi/group/DeleteSubgroups.java
+++ b/java/com/google/gerrit/server/restapi/group/DeleteSubgroups.java
@@ -77,7 +77,7 @@
     try {
       removeSubgroups(groupUuid, subgroupsToRemove);
     } catch (NoSuchGroupException e) {
-      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
     }
 
     return Response.none();
diff --git a/java/com/google/gerrit/server/restapi/group/GetOwner.java b/java/com/google/gerrit/server/restapi/group/GetOwner.java
index 30d5c16..e8bdfaa 100644
--- a/java/com/google/gerrit/server/restapi/group/GetOwner.java
+++ b/java/com/google/gerrit/server/restapi/group/GetOwner.java
@@ -47,7 +47,7 @@
       GroupControl c = controlFactory.validateFor(group.getOwnerGroupUUID());
       return Response.ok(json.format(c.getGroup()));
     } catch (NoSuchGroupException e) {
-      throw new ResourceNotFoundException();
+      throw new ResourceNotFoundException(group.getOwnerGroupUUID().get(), e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/restapi/group/PutDescription.java b/java/com/google/gerrit/server/restapi/group/PutDescription.java
index 98c773e..8fe4b20 100644
--- a/java/com/google/gerrit/server/restapi/group/PutDescription.java
+++ b/java/com/google/gerrit/server/restapi/group/PutDescription.java
@@ -66,7 +66,7 @@
       try {
         groupsUpdateProvider.get().updateGroup(groupUuid, groupUpdate);
       } catch (NoSuchGroupException e) {
-        throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+        throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
       }
     }
 
diff --git a/java/com/google/gerrit/server/restapi/group/PutName.java b/java/com/google/gerrit/server/restapi/group/PutName.java
index 802956a..9a3c87d 100644
--- a/java/com/google/gerrit/server/restapi/group/PutName.java
+++ b/java/com/google/gerrit/server/restapi/group/PutName.java
@@ -79,9 +79,9 @@
     try {
       groupsUpdateProvider.get().updateGroup(groupUuid, groupUpdate);
     } catch (NoSuchGroupException e) {
-      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+      throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
     } catch (DuplicateKeyException e) {
-      throw new ResourceConflictException("group with name " + newName + " already exists");
+      throw new ResourceConflictException("group with name " + newName + " already exists", e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/restapi/group/PutOptions.java b/java/com/google/gerrit/server/restapi/group/PutOptions.java
index c96972f..53bf571 100644
--- a/java/com/google/gerrit/server/restapi/group/PutOptions.java
+++ b/java/com/google/gerrit/server/restapi/group/PutOptions.java
@@ -66,7 +66,7 @@
       try {
         groupsUpdateProvider.get().updateGroup(groupUuid, groupUpdate);
       } catch (NoSuchGroupException e) {
-        throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+        throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
       }
     }
 
diff --git a/java/com/google/gerrit/server/restapi/group/PutOwner.java b/java/com/google/gerrit/server/restapi/group/PutOwner.java
index 709f7e3..04129af 100644
--- a/java/com/google/gerrit/server/restapi/group/PutOwner.java
+++ b/java/com/google/gerrit/server/restapi/group/PutOwner.java
@@ -77,7 +77,7 @@
       try {
         groupsUpdateProvider.get().updateGroup(groupUuid, groupUpdate);
       } catch (NoSuchGroupException e) {
-        throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid));
+        throw new ResourceNotFoundException(String.format("Group %s not found", groupUuid), e);
       }
     }
     return Response.ok(json.format(owner));
diff --git a/java/com/google/gerrit/server/restapi/project/BranchesCollection.java b/java/com/google/gerrit/server/restapi/project/BranchesCollection.java
index fe2fb0f..2d78bb0 100644
--- a/java/com/google/gerrit/server/restapi/project/BranchesCollection.java
+++ b/java/com/google/gerrit/server/restapi/project/BranchesCollection.java
@@ -82,9 +82,9 @@
           .check(RefPermission.READ);
       return new BranchResource(parent.getProjectState(), parent.getUser(), ref);
     } catch (AuthException notAllowed) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, notAllowed);
     } catch (RepositoryNotFoundException noRepo) {
-      throw new ResourceNotFoundException();
+      throw new ResourceNotFoundException(id, noRepo);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/project/CommitsCollection.java b/java/com/google/gerrit/server/restapi/project/CommitsCollection.java
index 757b650..21d7f0b 100644
--- a/java/com/google/gerrit/server/restapi/project/CommitsCollection.java
+++ b/java/com/google/gerrit/server/restapi/project/CommitsCollection.java
@@ -87,7 +87,7 @@
     try {
       objectId = ObjectId.fromString(id.get());
     } catch (IllegalArgumentException e) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, e);
     }
 
     try (Repository repo = repoManager.openRepository(parent.getNameKey());
@@ -102,7 +102,7 @@
       }
       return new CommitResource(parent, commit);
     } catch (MissingObjectException | IncorrectObjectTypeException e) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/project/CreateAccessChange.java b/java/com/google/gerrit/server/restapi/project/CreateAccessChange.java
index 76f1105..fe48301 100644
--- a/java/com/google/gerrit/server/restapi/project/CreateAccessChange.java
+++ b/java/com/google/gerrit/server/restapi/project/CreateAccessChange.java
@@ -102,7 +102,7 @@
       try {
         forProject.ref(RefNames.REFS_CONFIG).check(RefPermission.CREATE_CHANGE);
       } catch (AuthException denied) {
-        throw new AuthException("cannot create change for " + RefNames.REFS_CONFIG);
+        throw new AuthException("cannot create change for " + RefNames.REFS_CONFIG, denied);
       }
     }
     projectCache.checkedGet(rsrc.getNameKey()).checkStatePermitsWrite();
diff --git a/java/com/google/gerrit/server/restapi/project/CreateBranch.java b/java/com/google/gerrit/server/restapi/project/CreateBranch.java
index 67213c5..c15fdeb 100644
--- a/java/com/google/gerrit/server/restapi/project/CreateBranch.java
+++ b/java/com/google/gerrit/server/restapi/project/CreateBranch.java
@@ -127,7 +127,7 @@
         try {
           object = rw.parseCommit(object);
         } catch (IncorrectObjectTypeException notCommit) {
-          throw new BadRequestException("\"" + input.revision + "\" not a commit");
+          throw new BadRequestException("\"" + input.revision + "\" not a commit", notCommit);
         }
       }
 
@@ -197,7 +197,7 @@
         throw err;
       }
     } catch (RefUtil.InvalidRevisionException e) {
-      throw new BadRequestException("invalid revision \"" + input.revision + "\"");
+      throw new BadRequestException("invalid revision \"" + input.revision + "\"", e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/restapi/project/CreateTag.java b/java/com/google/gerrit/server/restapi/project/CreateTag.java
index 8fdf5e4..b087f15 100644
--- a/java/com/google/gerrit/server/restapi/project/CreateTag.java
+++ b/java/com/google/gerrit/server/restapi/project/CreateTag.java
@@ -149,7 +149,7 @@
         }
       }
     } catch (InvalidRevisionException e) {
-      throw new BadRequestException("Invalid base revision");
+      throw new BadRequestException("Invalid base revision", e);
     } catch (GitAPIException e) {
       logger.atSevere().withCause(e).log("Cannot create tag \"%s\"", ref);
       throw new IOException(e);
diff --git a/java/com/google/gerrit/server/restapi/project/DashboardsCollection.java b/java/com/google/gerrit/server/restapi/project/DashboardsCollection.java
index 606f3bef..ca48109 100644
--- a/java/com/google/gerrit/server/restapi/project/DashboardsCollection.java
+++ b/java/com/google/gerrit/server/restapi/project/DashboardsCollection.java
@@ -103,14 +103,14 @@
     try {
       info = newDashboardInfo(id.get());
     } catch (InvalidDashboardId e) {
-      throw new ResourceNotFoundException(id);
+      throw new ResourceNotFoundException(id, e);
     }
 
     for (ProjectState ps : parent.getProjectState().tree()) {
       try {
         return parse(ps, parent.getProjectState(), parent.getUser(), info);
       } catch (AmbiguousObjectException | ConfigInvalidException | IncorrectObjectTypeException e) {
-        throw new ResourceNotFoundException(id);
+        throw new ResourceNotFoundException(id, e);
       } catch (ResourceNotFoundException e) {
         continue;
       }
@@ -135,7 +135,7 @@
       permissionBackend.user(user).project(parent.getNameKey()).ref(ref).check(RefPermission.READ);
     } catch (AuthException e) {
       // Don't leak the project's existence
-      throw new ResourceNotFoundException(info.id);
+      throw new ResourceNotFoundException(info.id, e);
     }
     if (!Repository.isValidRefName(ref)) {
       throw new ResourceNotFoundException(info.id);
@@ -151,7 +151,7 @@
       BlobBasedConfig cfg = new BlobBasedConfig(null, git, objId);
       return new DashboardResource(current, user, ref, info.path, cfg, false);
     } catch (RepositoryNotFoundException e) {
-      throw new ResourceNotFoundException(info.id);
+      throw new ResourceNotFoundException(info.id, e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/project/GetAccess.java b/java/com/google/gerrit/server/restapi/project/GetAccess.java
index 550c4c4..a9a9403 100644
--- a/java/com/google/gerrit/server/restapi/project/GetAccess.java
+++ b/java/com/google/gerrit/server/restapi/project/GetAccess.java
@@ -165,7 +165,7 @@
     } catch (ConfigInvalidException e) {
       throw new ResourceConflictException(e.getMessage());
     } catch (RepositoryNotFoundException e) {
-      throw new ResourceNotFoundException(rsrc.getName());
+      throw new ResourceNotFoundException(rsrc.getName(), e);
     }
 
     // The following implementation must match the ProjectAccessFactory JSON RPC endpoint.
diff --git a/java/com/google/gerrit/server/restapi/project/GetHead.java b/java/com/google/gerrit/server/restapi/project/GetHead.java
index 928db97..4e0a144 100644
--- a/java/com/google/gerrit/server/restapi/project/GetHead.java
+++ b/java/com/google/gerrit/server/restapi/project/GetHead.java
@@ -82,13 +82,13 @@
                 .project(rsrc.getNameKey())
                 .check(ProjectPermission.WRITE_CONFIG);
           } catch (AuthException ae) {
-            throw new AuthException("not allowed to see HEAD");
+            throw new AuthException("not allowed to see HEAD", ae);
           }
         }
       }
       throw new ResourceNotFoundException(Constants.HEAD);
     } catch (RepositoryNotFoundException e) {
-      throw new ResourceNotFoundException(rsrc.getName());
+      throw new ResourceNotFoundException(rsrc.getName(), e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/restapi/project/GetReflog.java b/java/com/google/gerrit/server/restapi/project/GetReflog.java
index a249f26..f9c6fd9 100644
--- a/java/com/google/gerrit/server/restapi/project/GetReflog.java
+++ b/java/com/google/gerrit/server/restapi/project/GetReflog.java
@@ -104,7 +104,7 @@
       } catch (UnsupportedOperationException e) {
         String msg = "reflog not supported on repo " + rsrc.getNameKey().get();
         logger.atSevere().log(msg);
-        throw new MethodNotAllowedException(msg);
+        throw new MethodNotAllowedException(msg, e);
       }
       if (r == null) {
         throw new ResourceNotFoundException(rsrc.getRef());
diff --git a/java/com/google/gerrit/server/restapi/project/GetStatistics.java b/java/com/google/gerrit/server/restapi/project/GetStatistics.java
index d68e0af..db97855 100644
--- a/java/com/google/gerrit/server/restapi/project/GetStatistics.java
+++ b/java/com/google/gerrit/server/restapi/project/GetStatistics.java
@@ -51,7 +51,7 @@
     } catch (GitAPIException | JGitInternalException e) {
       throw new ResourceConflictException(e.getMessage());
     } catch (IOException e) {
-      throw new ResourceNotFoundException(rsrc.getName());
+      throw new ResourceNotFoundException(rsrc.getName(), e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/restapi/project/ListBranches.java b/java/com/google/gerrit/server/restapi/project/ListBranches.java
index cd20820..fecdc8e 100644
--- a/java/com/google/gerrit/server/restapi/project/ListBranches.java
+++ b/java/com/google/gerrit/server/restapi/project/ListBranches.java
@@ -149,7 +149,7 @@
       }
       return toBranchInfo(rsrc, ImmutableList.of(r)).get(0);
     } catch (RepositoryNotFoundException noRepo) {
-      throw new ResourceNotFoundException();
+      throw new ResourceNotFoundException(rsrc.getNameKey().get(), noRepo);
     }
   }
 
@@ -165,7 +165,7 @@
               .exactRef(Constants.HEAD, RefNames.REFS_CONFIG, RefNames.REFS_USERS_DEFAULT)
               .values());
     } catch (RepositoryNotFoundException noGitRepository) {
-      throw new ResourceNotFoundException();
+      throw new ResourceNotFoundException(rsrc.getNameKey().get(), noGitRepository);
     }
     return toBranchInfo(rsrc, refs);
   }
diff --git a/java/com/google/gerrit/server/restapi/project/ListDashboards.java b/java/com/google/gerrit/server/restapi/project/ListDashboards.java
index 058083c..4406719 100644
--- a/java/com/google/gerrit/server/restapi/project/ListDashboards.java
+++ b/java/com/google/gerrit/server/restapi/project/ListDashboards.java
@@ -120,7 +120,7 @@
       }
       return all;
     } catch (RepositoryNotFoundException e) {
-      throw new ResourceNotFoundException();
+      throw new ResourceNotFoundException(project, e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/project/ListTags.java b/java/com/google/gerrit/server/restapi/project/ListTags.java
index 8cea7f5..123c78a 100644
--- a/java/com/google/gerrit/server/restapi/project/ListTags.java
+++ b/java/com/google/gerrit/server/restapi/project/ListTags.java
@@ -219,7 +219,7 @@
     try {
       return repoManager.openRepository(project);
     } catch (RepositoryNotFoundException noGitRepository) {
-      throw new ResourceNotFoundException();
+      throw new ResourceNotFoundException(project.get(), noGitRepository);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/project/PutConfig.java b/java/com/google/gerrit/server/restapi/project/PutConfig.java
index a0badd7..9f9433b 100644
--- a/java/com/google/gerrit/server/restapi/project/PutConfig.java
+++ b/java/com/google/gerrit/server/restapi/project/PutConfig.java
@@ -190,7 +190,7 @@
           uiActions,
           views);
     } catch (RepositoryNotFoundException notFound) {
-      throw new ResourceNotFoundException(projectName.get());
+      throw new ResourceNotFoundException(projectName.get(), notFound);
     } catch (ConfigInvalidException err) {
       throw new ResourceConflictException("Cannot read project " + projectName, err);
     } catch (IOException err) {
diff --git a/java/com/google/gerrit/server/restapi/project/PutDescription.java b/java/com/google/gerrit/server/restapi/project/PutDescription.java
index 0281b8d..a0b9feb 100644
--- a/java/com/google/gerrit/server/restapi/project/PutDescription.java
+++ b/java/com/google/gerrit/server/restapi/project/PutDescription.java
@@ -92,7 +92,7 @@
           ? Response.none()
           : Response.ok(project.getDescription());
     } catch (RepositoryNotFoundException notFound) {
-      throw new ResourceNotFoundException(resource.getName());
+      throw new ResourceNotFoundException(resource.getName(), notFound);
     } catch (ConfigInvalidException e) {
       throw new ResourceConflictException(
           String.format("invalid project.config: %s", e.getMessage()));
diff --git a/java/com/google/gerrit/server/restapi/project/SetAccess.java b/java/com/google/gerrit/server/restapi/project/SetAccess.java
index f8c7234..02c1b54 100644
--- a/java/com/google/gerrit/server/restapi/project/SetAccess.java
+++ b/java/com/google/gerrit/server/restapi/project/SetAccess.java
@@ -130,7 +130,7 @@
     } catch (InvalidNameException e) {
       throw new BadRequestException(e.toString());
     } catch (ConfigInvalidException e) {
-      throw new ResourceConflictException(rsrc.getName());
+      throw new ResourceConflictException(rsrc.getName(), e);
     }
 
     return Response.ok(getAccess.apply(rsrc.getNameKey()));
diff --git a/java/com/google/gerrit/server/restapi/project/SetDefaultDashboard.java b/java/com/google/gerrit/server/restapi/project/SetDefaultDashboard.java
index 8879fae..9920be0 100644
--- a/java/com/google/gerrit/server/restapi/project/SetDefaultDashboard.java
+++ b/java/com/google/gerrit/server/restapi/project/SetDefaultDashboard.java
@@ -89,7 +89,7 @@
                 new ProjectResource(rsrc.getProjectState(), rsrc.getUser()),
                 IdString.fromUrl(input.id));
       } catch (ResourceNotFoundException e) {
-        throw new BadRequestException("dashboard " + input.id + " not found");
+        throw new BadRequestException("dashboard " + input.id + " not found", e);
       } catch (ConfigInvalidException e) {
         throw new ResourceConflictException(e.getMessage());
       }
@@ -125,7 +125,7 @@
       }
       return Response.none();
     } catch (RepositoryNotFoundException notFound) {
-      throw new ResourceNotFoundException(rsrc.getProjectState().getProject().getName());
+      throw new ResourceNotFoundException(rsrc.getProjectState().getProject().getName(), notFound);
     } catch (ConfigInvalidException e) {
       throw new ResourceConflictException(
           String.format("invalid project.config: %s", e.getMessage()));
diff --git a/java/com/google/gerrit/server/restapi/project/SetHead.java b/java/com/google/gerrit/server/restapi/project/SetHead.java
index 946695e..ae70e46 100644
--- a/java/com/google/gerrit/server/restapi/project/SetHead.java
+++ b/java/com/google/gerrit/server/restapi/project/SetHead.java
@@ -114,7 +114,7 @@
       }
       return Response.ok(ref);
     } catch (RepositoryNotFoundException e) {
-      throw new ResourceNotFoundException(rsrc.getName());
+      throw new ResourceNotFoundException(rsrc.getName(), e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/restapi/project/SetParent.java b/java/com/google/gerrit/server/restapi/project/SetParent.java
index 7241fcf..4cf0182 100644
--- a/java/com/google/gerrit/server/restapi/project/SetParent.java
+++ b/java/com/google/gerrit/server/restapi/project/SetParent.java
@@ -121,7 +121,7 @@
       requireNonNull(parent);
       return parent.get();
     } catch (RepositoryNotFoundException notFound) {
-      throw new ResourceNotFoundException(rsrc.getName());
+      throw new ResourceNotFoundException(rsrc.getName(), notFound);
     } catch (ConfigInvalidException e) {
       throw new ResourceConflictException(
           String.format("invalid project.config: %s", e.getMessage()));
diff --git a/java/com/google/gerrit/server/rules/StoredValues.java b/java/com/google/gerrit/server/rules/StoredValues.java
index 085475e..1e08a24 100644
--- a/java/com/google/gerrit/server/rules/StoredValues.java
+++ b/java/com/google/gerrit/server/rules/StoredValues.java
@@ -57,7 +57,8 @@
     try {
       return cd.change();
     } catch (StorageException e) {
-      throw new SystemException("Cannot load change " + cd.getId());
+      throw new SystemException(
+          String.format("Cannot load change %s: %s", cd.getId(), e.getMessage()));
     }
   }
 
@@ -101,7 +102,7 @@
           try {
             patchList = plCache.get(plKey, project);
           } catch (PatchListNotAvailableException e) {
-            throw new SystemException("Cannot create " + plKey);
+            throw new SystemException(String.format("Cannot create %s: %s", plKey, e.getMessage()));
           }
           return patchList;
         }
diff --git a/java/com/google/gerrit/server/schema/NoteDbSchemaUpdater.java b/java/com/google/gerrit/server/schema/NoteDbSchemaUpdater.java
index 5dec581..0e22af9 100644
--- a/java/com/google/gerrit/server/schema/NoteDbSchemaUpdater.java
+++ b/java/com/google/gerrit/server/schema/NoteDbSchemaUpdater.java
@@ -104,7 +104,7 @@
     try {
       schemaCreator.ensureCreated();
     } catch (IOException | ConfigInvalidException e) {
-      throw new StorageException("Cannot initialize Gerrit site");
+      throw new StorageException("Cannot initialize Gerrit site", e);
     }
   }
 
diff --git a/java/com/google/gerrit/server/submit/RebaseSubmitStrategy.java b/java/com/google/gerrit/server/submit/RebaseSubmitStrategy.java
index a6e01af..65e18ad 100644
--- a/java/com/google/gerrit/server/submit/RebaseSubmitStrategy.java
+++ b/java/com/google/gerrit/server/submit/RebaseSubmitStrategy.java
@@ -161,7 +161,8 @@
         } catch (MergeConflictException mce) {
           // Unlike in Cherry-pick case, this should never happen.
           toMerge.setStatusCode(CommitMergeStatus.REBASE_MERGE_CONFLICT);
-          throw new IllegalStateException("MergeConflictException on message edit must not happen");
+          throw new IllegalStateException(
+              "MergeConflictException on message edit must not happen", mce);
         } catch (MergeIdenticalTreeException mie) {
           // this should not happen
           toMerge.setStatusCode(SKIPPED_IDENTICAL_TREE);
diff --git a/java/com/google/gerrit/server/submit/SubmitStrategyOp.java b/java/com/google/gerrit/server/submit/SubmitStrategyOp.java
index 6be4a91..cc40a30 100644
--- a/java/com/google/gerrit/server/submit/SubmitStrategyOp.java
+++ b/java/com/google/gerrit/server/submit/SubmitStrategyOp.java
@@ -550,7 +550,7 @@
       return args.submoduleOp.composeGitlinksCommit(args.destBranch, commit);
     } catch (SubmoduleException | IOException e) {
       throw new IntegrationException(
-          "cannot update gitlink for the commit at branch: " + args.destBranch);
+          "cannot update gitlink for the commit at branch: " + args.destBranch, e);
     }
   }
 }
diff --git a/java/com/google/gerrit/server/util/SocketUtil.java b/java/com/google/gerrit/server/util/SocketUtil.java
index afa2aee..e617650 100644
--- a/java/com/google/gerrit/server/util/SocketUtil.java
+++ b/java/com/google/gerrit/server/util/SocketUtil.java
@@ -96,7 +96,7 @@
       try {
         port = Integer.parseInt(portStr);
       } catch (NumberFormatException e) {
-        throw new IllegalArgumentException("invalid port: " + desc);
+        throw new IllegalArgumentException("invalid port: " + desc, e);
       }
     } else {
       port = defaultPort;
diff --git a/java/com/google/gerrit/sshd/BaseCommand.java b/java/com/google/gerrit/sshd/BaseCommand.java
index ac22dfc..5d7dba2 100644
--- a/java/com/google/gerrit/sshd/BaseCommand.java
+++ b/java/com/google/gerrit/sshd/BaseCommand.java
@@ -387,6 +387,10 @@
     return new UnloggedFailure(1, "fatal: " + msg);
   }
 
+  protected UnloggedFailure die(String msg, Throwable why) {
+    return new UnloggedFailure(1, "fatal: " + msg, why);
+  }
+
   protected UnloggedFailure die(Throwable why) {
     return new UnloggedFailure(1, "fatal: " + why.getMessage(), why);
   }
diff --git a/java/com/google/gerrit/sshd/ChangeArgumentParser.java b/java/com/google/gerrit/sshd/ChangeArgumentParser.java
index c273b4c..491bcb8 100644
--- a/java/com/google/gerrit/sshd/ChangeArgumentParser.java
+++ b/java/com/google/gerrit/sshd/ChangeArgumentParser.java
@@ -111,7 +111,7 @@
     try {
       changeResource = changesCollection.parse(cId);
     } catch (RestApiException e) {
-      throw new UnloggedFailure(1, "\"" + id + "\" no such change");
+      throw new UnloggedFailure(1, "\"" + id + "\" no such change", e);
     }
     changes.put(cId, changeResource);
   }
diff --git a/java/com/google/gerrit/sshd/SshKeyCreatorImpl.java b/java/com/google/gerrit/sshd/SshKeyCreatorImpl.java
index e6c3a40..02a9e48 100644
--- a/java/com/google/gerrit/sshd/SshKeyCreatorImpl.java
+++ b/java/com/google/gerrit/sshd/SshKeyCreatorImpl.java
@@ -34,11 +34,10 @@
       SshUtil.parse(key);
       return key;
     } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
-      throw new InvalidSshKeyException();
-
+      throw new InvalidSshKeyException(e);
     } catch (NoSuchProviderException e) {
       logger.atSevere().withCause(e).log("Cannot parse SSH key");
-      throw new InvalidSshKeyException();
+      throw new InvalidSshKeyException(e);
     }
   }
 }
diff --git a/java/com/google/gerrit/sshd/SuExec.java b/java/com/google/gerrit/sshd/SuExec.java
index f485bd7..ea163d5 100644
--- a/java/com/google/gerrit/sshd/SuExec.java
+++ b/java/com/google/gerrit/sshd/SuExec.java
@@ -127,9 +127,9 @@
       try {
         permissionBackend.user(caller).check(GlobalPermission.RUN_AS);
       } catch (AuthException e) {
-        throw die("suexec not permitted");
+        throw die("suexec not permitted", e);
       } catch (PermissionBackendException e) {
-        throw die("suexec not available: " + e);
+        throw die("suexec not available", e);
       }
     }
   }
diff --git a/java/com/google/gerrit/sshd/commands/LsUserRefs.java b/java/com/google/gerrit/sshd/commands/LsUserRefs.java
index b4a2b42..80aee01 100644
--- a/java/com/google/gerrit/sshd/commands/LsUserRefs.java
+++ b/java/com/google/gerrit/sshd/commands/LsUserRefs.java
@@ -104,9 +104,9 @@
         throw new Failure(1, "fatal: Error reading refs: '" + projectName, e);
       }
     } catch (RepositoryNotFoundException e) {
-      throw die("'" + projectName + "': not a git archive");
+      throw die("'" + projectName + "': not a git archive", e);
     } catch (IOException e) {
-      throw die("Error opening: '" + projectName);
+      throw die("Error opening: '" + projectName, e);
     }
   }
 }
diff --git a/java/com/google/gerrit/sshd/commands/PatchSetParser.java b/java/com/google/gerrit/sshd/commands/PatchSetParser.java
index e40ab87..f804c2d 100644
--- a/java/com/google/gerrit/sshd/commands/PatchSetParser.java
+++ b/java/com/google/gerrit/sshd/commands/PatchSetParser.java
@@ -99,7 +99,7 @@
       try {
         patchSetId = PatchSet.Id.parse(token);
       } catch (IllegalArgumentException e) {
-        throw error("\"" + token + "\" is not a valid patch set");
+        throw error("\"" + token + "\" is not a valid patch set", e);
       }
       ChangeNotes notes = getNotes(projectState, patchSetId.changeId());
       PatchSet patchSet = psUtil.get(notes, patchSetId);
@@ -130,7 +130,7 @@
       ChangeNotes notes = changeFinder.findOne(changeId);
       return notesFactory.create(notes.getProjectName(), changeId);
     } catch (NoSuchChangeException e) {
-      throw error("\"" + changeId + "\" no such change");
+      throw error("\"" + changeId + "\" no such change", e);
     }
   }
 
@@ -153,4 +153,8 @@
   public static UnloggedFailure error(String msg) {
     return new UnloggedFailure(1, msg);
   }
+
+  public static UnloggedFailure error(String msg, Throwable why) {
+    return new UnloggedFailure(1, msg, why);
+  }
 }
diff --git a/java/com/google/gerrit/sshd/commands/PluginInstallCommand.java b/java/com/google/gerrit/sshd/commands/PluginInstallCommand.java
index 8b045ec..cfb47f7 100644
--- a/java/com/google/gerrit/sshd/commands/PluginInstallCommand.java
+++ b/java/com/google/gerrit/sshd/commands/PluginInstallCommand.java
@@ -70,21 +70,21 @@
       try {
         data = Files.newInputStream(new File(source).toPath());
       } catch (IOException e) {
-        throw die("cannot read " + source);
+        throw die("cannot read " + source, e);
       }
     } else {
       try {
         data = new URL(source).openStream();
       } catch (MalformedURLException e) {
-        throw die("invalid url " + source);
+        throw die("invalid url " + source, e);
       } catch (IOException e) {
-        throw die("cannot read " + source);
+        throw die("cannot read " + source, e);
       }
     }
     try {
       loader.installPluginFromStream(name, data);
     } catch (IOException e) {
-      throw die("cannot install plugin");
+      throw die("cannot install plugin", e);
     } catch (PluginInstallException e) {
       e.printStackTrace(stderr);
       String msg = String.format("Plugin failed to install. Cause: %s", e.getMessage());
diff --git a/java/com/google/gerrit/sshd/commands/Receive.java b/java/com/google/gerrit/sshd/commands/Receive.java
index e2fb633..6791b70 100644
--- a/java/com/google/gerrit/sshd/commands/Receive.java
+++ b/java/com/google/gerrit/sshd/commands/Receive.java
@@ -78,7 +78,7 @@
           .project(project.getNameKey())
           .check(ProjectPermission.RUN_RECEIVE_PACK);
     } catch (AuthException e) {
-      throw new Failure(1, "fatal: receive-pack not permitted on this server");
+      throw new Failure(1, "fatal: receive-pack not permitted on this server", e);
     } catch (PermissionBackendException e) {
       throw new Failure(1, "fatal: unable to check permissions " + e);
     }
diff --git a/java/com/google/gerrit/sshd/commands/ReviewCommand.java b/java/com/google/gerrit/sshd/commands/ReviewCommand.java
index 886f21e..3a1bf6c 100644
--- a/java/com/google/gerrit/sshd/commands/ReviewCommand.java
+++ b/java/com/google/gerrit/sshd/commands/ReviewCommand.java
@@ -327,7 +327,7 @@
     try {
       allProjectsState = projectCache.checkedGet(allProjects);
     } catch (IOException e) {
-      throw die("missing " + allProjects.get());
+      throw die("missing " + allProjects.get(), e);
     }
 
     for (LabelType type : allProjectsState.getLabelTypes().getLabelTypes()) {
diff --git a/java/com/google/gerrit/sshd/commands/Upload.java b/java/com/google/gerrit/sshd/commands/Upload.java
index 87ae493..6c4e80a 100644
--- a/java/com/google/gerrit/sshd/commands/Upload.java
+++ b/java/com/google/gerrit/sshd/commands/Upload.java
@@ -61,9 +61,9 @@
     try {
       perm.check(ProjectPermission.RUN_UPLOAD_PACK);
     } catch (AuthException e) {
-      throw new Failure(1, "fatal: upload-pack not permitted on this server");
+      throw new Failure(1, "fatal: upload-pack not permitted on this server", e);
     } catch (PermissionBackendException e) {
-      throw new Failure(1, "fatal: unable to check permissions " + e);
+      throw new Failure(1, "fatal: unable to check permissions ", e);
     }
 
     Repository permissionAwareRepo = PermissionAwareRepositoryManager.wrap(repo, perm);
diff --git a/plugins/BUILD b/plugins/BUILD
index ccb97e8..8d9682f 100644
--- a/plugins/BUILD
+++ b/plugins/BUILD
@@ -93,7 +93,18 @@
 ]
 
 java_binary(
+    name = "bouncycastle-deploy-env",
+    main_class = "Dummy",
+    runtime_deps = [
+        "//lib/bouncycastle:bcpg",
+        "//lib/bouncycastle:bcpkix",
+        "//lib/bouncycastle:bcprov",
+    ],
+)
+
+java_binary(
     name = "plugin-api",
+    deploy_env = ["bouncycastle-deploy-env"],
     main_class = "Dummy",
     visibility = ["//visibility:public"],
     runtime_deps = [":plugin-lib"],
diff --git a/plugins/delete-project b/plugins/delete-project
index 7885a9f..180fd9d 160000
--- a/plugins/delete-project
+++ b/plugins/delete-project
@@ -1 +1 @@
-Subproject commit 7885a9fa8d262b6127a7a3aa294108d6aac47a4d
+Subproject commit 180fd9dbd7f1661d16bf05ca8a16c74bfcc9bc67
diff --git a/plugins/replication b/plugins/replication
index 90ca234..0bf9f5a 160000
--- a/plugins/replication
+++ b/plugins/replication
@@ -1 +1 @@
-Subproject commit 90ca234c456767b79608ad2254f3e80f02f308ca
+Subproject commit 0bf9f5ae26220bfdcff0b3332e810f00aa9a7789
diff --git a/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html b/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
index 72f5d5b..76d12e9 100644
--- a/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
+++ b/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
@@ -321,12 +321,13 @@
             element.fire('show-alert', {
               message: 'test-alert', action: 'reload',
             });
-            toast = toastSpy.lastCall.returnValue;
-            assert.isOk(toast);
-            assert.include(
-                Polymer.dom(toast.root).textContent, 'Credentails expired.');
-
-            done();
+            flush(() => {
+              toast = toastSpy.lastCall.returnValue;
+              assert.isOk(toast);
+              assert.include(
+                  Polymer.dom(toast.root).textContent, 'Credentails expired.');
+              done();
+            });
           });
         });
       });
diff --git a/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor.js b/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor.js
index 05a7525..726ac10 100644
--- a/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor.js
+++ b/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor.js
@@ -237,6 +237,11 @@
       this.moveToNextChunk(true);
     }
 
+    moveToLastChunk() {
+      this.$.cursorManager.moveToEnd();
+      this.moveToPreviousChunk();
+    }
+
     reInitCursor() {
       this._updateStops();
       if (this.initialLineNumber) {
diff --git a/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor_test.html b/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor_test.html
index dff9e79..24ca3d1 100644
--- a/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor_test.html
+++ b/polygerrit-ui/app/elements/diff/gr-diff-cursor/gr-diff-cursor_test.html
@@ -108,6 +108,18 @@
       assert.equal(cursorElement.diffRow, firstDeltaRow);
     });
 
+    test('moveToLastChunk', () => {
+      const chunks = Array.from(Polymer.dom(diffElement.root).querySelectorAll(
+          '.section.delta'));
+      assert.isAbove(chunks.length, 1);
+      assert.equal(chunks.indexOf(cursorElement.diffRow.parentElement), 0);
+
+      cursorElement.moveToLastChunk();
+
+      assert.equal(chunks.indexOf(cursorElement.diffRow.parentElement),
+          chunks.length - 1);
+    });
+
     test('cursor scroll behavior', () => {
       cursorElement._handleDiffRenderStart();
       assert.equal(cursorElement._scrollBehavior, 'keep-visible');
diff --git a/polygerrit-ui/app/elements/shared/gr-button/gr-button.html b/polygerrit-ui/app/elements/shared/gr-button/gr-button.html
index fd75c7c..7cac2d8 100644
--- a/polygerrit-ui/app/elements/shared/gr-button/gr-button.html
+++ b/polygerrit-ui/app/elements/shared/gr-button/gr-button.html
@@ -21,6 +21,7 @@
 <link rel="import" href="../../../behaviors/keyboard-shortcut-behavior/keyboard-shortcut-behavior.html">
 <link rel="import" href="/bower_components/paper-button/paper-button.html">
 <link rel="import" href="../../../styles/shared-styles.html">
+<link rel="import" href="../../core/gr-reporting/gr-reporting.html">
 
 <dom-module id="gr-button">
   <template strip-whitespace>
@@ -160,6 +161,7 @@
       <slot></slot>
       <i class="downArrow"></i>
     </paper-button>
+    <gr-reporting id="reporting"></gr-reporting>
   </template>
   <script src="gr-button.js"></script>
 </dom-module>
diff --git a/polygerrit-ui/app/elements/shared/gr-button/gr-button.js b/polygerrit-ui/app/elements/shared/gr-button/gr-button.js
index abfbb18..681717f 100644
--- a/polygerrit-ui/app/elements/shared/gr-button/gr-button.js
+++ b/polygerrit-ui/app/elements/shared/gr-button/gr-button.js
@@ -90,6 +90,19 @@
         e.preventDefault();
         e.stopImmediatePropagation();
       }
+      let el = this.root;
+      let path = '';
+      while (el = el.parentNode || el.host) {
+        if (el.tagName && el.tagName.startsWith('GR-APP')) {
+          break;
+        }
+        if (el.tagName) {
+          const idString = el.id ? '#' + el.id : '';
+          path = el.tagName + idString + ' ' + path;
+        }
+      }
+      this.$.reporting.reportInteraction('button-click',
+          path.trim().toLowerCase());
     }
 
     _disabledChanged(disabled) {
diff --git a/polygerrit-ui/app/elements/shared/gr-cursor-manager/gr-cursor-manager.js b/polygerrit-ui/app/elements/shared/gr-cursor-manager/gr-cursor-manager.js
index 374204b..fd70fd9 100644
--- a/polygerrit-ui/app/elements/shared/gr-cursor-manager/gr-cursor-manager.js
+++ b/polygerrit-ui/app/elements/shared/gr-cursor-manager/gr-cursor-manager.js
@@ -163,6 +163,12 @@
       }
     }
 
+    moveToEnd() {
+      if (this.stops.length) {
+        this.setCursor(this.stops[this.stops.length - 1]);
+      }
+    }
+
     setCursorAtIndex(index, opt_noScroll) {
       this.setCursor(this.stops[index], opt_noScroll);
     }
diff --git a/polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-plugin-action-context_test.html b/polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-plugin-action-context_test.html
index f7b7cf8..ca43fc0 100644
--- a/polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-plugin-action-context_test.html
+++ b/polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-plugin-action-context_test.html
@@ -88,13 +88,17 @@
       assert.equal(div.textContent, 'foobar');
     });
 
-    test('button', () => {
+    test('button', done => {
       const clickStub = sandbox.stub();
       const button = instance.button('foo', {onclick: clickStub});
+      // If you don't attach a Polymer element to the DOM, then the ready()
+      // callback will not be called and then e.g. this.$ is undefined.
+      Polymer.dom(document.body).appendChild(button);
       MockInteractions.tap(button);
       flush(() => {
         assert.isTrue(clickStub.called);
         assert.equal(button.textContent, 'foo');
+        done();
       });
     });
 
diff --git a/tools/BUILD b/tools/BUILD
index 32599aa..2d702fe 100644
--- a/tools/BUILD
+++ b/tools/BUILD
@@ -86,6 +86,7 @@
         "-Xep:TypeParameterShadowing:ERROR",
         "-Xep:TypeParameterUnusedInFormals:ERROR",
         "-Xep:URLEqualsHashCode:ERROR",
+        "-Xep:UnusedException:ERROR",
         "-Xep:UnsynchronizedOverridesSynchronized:ERROR",
         "-Xep:WaitNotInLoop:ERROR",
         "-Xep:WildcardImport:ERROR",