-
Notifications
You must be signed in to change notification settings - Fork 134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement Error Prone ThrowError
to discourage throwing Errors in production code
#957
Changes from 3 commits
a3494b5
0dfcca6
df5a245
6386b56
027e340
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
/* | ||
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.palantir.baseline.errorprone; | ||
|
||
import com.google.auto.service.AutoService; | ||
import com.google.errorprone.BugPattern; | ||
import com.google.errorprone.VisitorState; | ||
import com.google.errorprone.bugpatterns.BugChecker; | ||
import com.google.errorprone.fixes.SuggestedFix; | ||
import com.google.errorprone.fixes.SuggestedFixes; | ||
import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher; | ||
import com.google.errorprone.matchers.Description; | ||
import com.google.errorprone.matchers.Matcher; | ||
import com.google.errorprone.util.ASTHelpers; | ||
import com.sun.source.tree.ExpressionTree; | ||
import com.sun.source.tree.NewClassTree; | ||
import com.sun.source.tree.ThrowTree; | ||
import com.sun.tools.javac.code.Type; | ||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
@AutoService(BugChecker.class) | ||
@BugPattern( | ||
name = "ThrowError", | ||
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", | ||
linkType = BugPattern.LinkType.CUSTOM, | ||
severity = BugPattern.SeverityLevel.WARNING, | ||
summary = "Prefer throwing a RuntimeException rather than Error. Errors are often handled poorly by libraries " | ||
+ "resulting in unexpected behavior and resource leaks. It's not obvious that " | ||
+ "'catch (Exception e)' does not catch Error.\n" | ||
+ "Errors are normally thrown by the JVM when the system, not just the application, " | ||
+ "is in a bad state. For example, LinkageError is thrown by the JVM when it encounters " | ||
+ "incompatible classes, and OutOfMemoryError when allocations fail. These should be " | ||
+ "less common and handled differently from application failures.\n" | ||
+ "This check is intended to be advisory - it's fine to @SuppressWarnings(\"ThrowError\") " | ||
+ "in certain cases, but is usually not recommended unless you are writing a testing library " | ||
+ "that throws AssertionError.") | ||
public final class ThrowError extends BugChecker implements BugChecker.ThrowTreeMatcher { | ||
|
||
private static final Matcher<ExpressionTree> compileTimeConstExpressionMatcher = | ||
new CompileTimeConstantExpressionMatcher(); | ||
private static final String ERROR_NAME = Error.class.getName(); | ||
|
||
@Override | ||
public Description matchThrow(ThrowTree tree, VisitorState state) { | ||
ExpressionTree expression = tree.getExpression(); | ||
if (!(expression instanceof NewClassTree)) { | ||
return Description.NO_MATCH; | ||
} | ||
NewClassTree newClassTree = (NewClassTree) expression; | ||
Type throwableType = ASTHelpers.getType(newClassTree.getIdentifier()); | ||
if (!ASTHelpers.isCastable( | ||
throwableType, | ||
state.getTypeFromString(ERROR_NAME), | ||
state) | ||
// Don't discourage developers from testing edge cases involving Errors. | ||
// It's also fine for tests throw AssertionError internally in test objects. | ||
|| TestCheckUtils.isTestCode(state)) { | ||
iamdanfox marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return Description.NO_MATCH; | ||
} | ||
return buildDescription(tree) | ||
.addFix(generateFix(newClassTree, state)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm a tiny bit worried this auto-fix is gonna funnel states which would previously crash-the-server into other existing error-handling flows (e.g. if a codebases catches RuntimeException further up), leading to a server limping along when it should really die quickly? -throw new AssertionError("Unknown classification operator");
+throw new IllegalStateException("Unknown classification operator"); There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. None of our servers really do that -- when we throw error in a conjure service we allow the server to log it and return an empty 500 response. We should probably log it and return 500 instead, adding an errorId, but the server doesn't react differently otherwise. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I do think we want developers to review these migration without mindlessly merging, but there are a lot of cases where error isn't handled properly (we had two p0s last week from this) |
||
.build(); | ||
} | ||
|
||
private static Optional<SuggestedFix> generateFix(NewClassTree newClassTree, VisitorState state) { | ||
Type throwableType = ASTHelpers.getType(newClassTree.getIdentifier()); | ||
// AssertionError is the most common failure case we've encountered, likely because it sounds | ||
// similar to IllegalStateException. In this case we suggest replacing it with IllegalStateException. | ||
if (!ASTHelpers.isSameType( | ||
throwableType, | ||
state.getTypeFromString(AssertionError.class.getName()), | ||
state)) { | ||
return Optional.empty(); | ||
} | ||
List<? extends ExpressionTree> arguments = newClassTree.getArguments(); | ||
if (arguments.isEmpty()) { | ||
SuggestedFix.Builder fix = SuggestedFix.builder(); | ||
String qualifiedName = SuggestedFixes.qualifyType(state, fix, IllegalStateException.class.getName()); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should we use SafeIllegalStateException and maybe hand it a message of "assertion failure"? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I matched semantics of the PreferSafeLoggablExceptions check which uses the non-logsafe exception type when there is no message. I don't have a strong preference, but I'm not sure using the safe type provides any additional information. |
||
return Optional.of(fix.replace(newClassTree.getIdentifier(), qualifiedName).build()); | ||
} | ||
ExpressionTree firstArgument = arguments.get(0); | ||
if (ASTHelpers.isSameType( | ||
ASTHelpers.getResultType(firstArgument), | ||
state.getTypeFromString(String.class.getName()), | ||
state)) { | ||
SuggestedFix.Builder fix = SuggestedFix.builder(); | ||
String qualifiedName = SuggestedFixes.qualifyType(state, fix, | ||
compileTimeConstExpressionMatcher.matches(firstArgument, state) | ||
? "com.palantir.logsafe.exceptions.SafeIllegalStateException" | ||
: IllegalStateException.class.getName()); | ||
return Optional.of(fix.replace(newClassTree.getIdentifier(), qualifiedName).build()); | ||
} | ||
return Optional.empty(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
/* | ||
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.palantir.baseline.errorprone; | ||
|
||
import com.google.errorprone.BugCheckerRefactoringTestHelper; | ||
import com.google.errorprone.CompilationTestHelper; | ||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.parallel.Execution; | ||
import org.junit.jupiter.api.parallel.ExecutionMode; | ||
|
||
@Execution(ExecutionMode.CONCURRENT) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 😍 |
||
class ThrowErrorTest { | ||
|
||
@Test | ||
void testAssertionError() { | ||
helper().addSourceLines( | ||
"Test.java", | ||
"class Test {", | ||
" void f() {", | ||
" // BUG: Diagnostic contains: Prefer throwing a RuntimeException", | ||
" throw new AssertionError();", | ||
" }", | ||
"}" | ||
).doTest(); | ||
} | ||
|
||
@Test | ||
void testError() { | ||
helper().addSourceLines( | ||
"Test.java", | ||
"class Test {", | ||
" void f() {", | ||
" // BUG: Diagnostic contains: Prefer throwing a RuntimeException", | ||
" throw new Error();", | ||
" }", | ||
"}" | ||
).doTest(); | ||
} | ||
|
||
@Test | ||
void testError_testCode() { | ||
// It's common to avoid handling Error by catching and rethrowing, this should be allowed. This check | ||
// is meant to dissuade developers from creating and throwing new Errors. | ||
helper().addSourceLines( | ||
"TestCase.java", | ||
"import " + Test.class.getName() + ';', | ||
"class TestCase {", | ||
" @Test", | ||
" void f() {", | ||
" throw new Error();", | ||
" }", | ||
"}" | ||
).doTest(); | ||
} | ||
|
||
@Test | ||
void testRethrowIsAllowed() { | ||
helper().addSourceLines( | ||
"Test.java", | ||
"class Test {", | ||
" void f(Error e) {", | ||
" throw e;", | ||
" }", | ||
"}" | ||
).doTest(); | ||
} | ||
|
||
@Test | ||
void testFix() { | ||
fix() | ||
.addInputLines( | ||
"Test.java", | ||
"class Test {", | ||
" void f1() {", | ||
" throw new AssertionError();", | ||
" }", | ||
" void f2(String nonConstant) {", | ||
" throw new AssertionError(nonConstant);", | ||
" }", | ||
" void f3() {", | ||
" throw new AssertionError(\"constant\");", | ||
" }", | ||
" void f4(String nonConstant, Throwable t) {", | ||
" throw new AssertionError(nonConstant, t);", | ||
" }", | ||
" void f5(Throwable t) {", | ||
" throw new AssertionError(\"constant\", t);", | ||
" }", | ||
"}") | ||
.addOutputLines( | ||
"Test.java", | ||
"import com.palantir.logsafe.exceptions.SafeIllegalStateException;", | ||
"class Test {", | ||
" void f1() {", | ||
" throw new IllegalStateException();", | ||
" }", | ||
" void f2(String nonConstant) {", | ||
" throw new IllegalStateException(nonConstant);", | ||
" }", | ||
" void f3() {", | ||
" throw new SafeIllegalStateException(\"constant\");", | ||
" }", | ||
" void f4(String nonConstant, Throwable t) {", | ||
" throw new IllegalStateException(nonConstant, t);", | ||
" }", | ||
" void f5(Throwable t) {", | ||
" throw new SafeIllegalStateException(\"constant\", t);", | ||
" }", | ||
"}") | ||
.doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH); | ||
} | ||
|
||
private CompilationTestHelper helper() { | ||
return CompilationTestHelper.newInstance(ThrowError.class, getClass()); | ||
} | ||
|
||
private BugCheckerRefactoringTestHelper fix() { | ||
return BugCheckerRefactoringTestHelper.newInstance(new ThrowError(), getClass()); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
type: improvement | ||
improvement: | ||
description: |- | ||
Implement Error Prone `ThrowError` to discourage throwing Errors in production code | ||
Errors are often handled poorly by libraries resulting in unexpected | ||
behavior and resource leaks. It's not obvious that 'catch (Exception e)' | ||
does not catch Error. | ||
This check is intended to be advisory - it's fine to | ||
`@SuppressWarnings("ThrowError")` in certain cases, but is usually not | ||
recommended unless you are writing a testing library that throws | ||
AssertionError. | ||
links: | ||
- https://github.com/palantir/gradle-baseline/pull/957 |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -34,6 +34,7 @@ public class BaselineErrorProneExtension { | |
"PreferSafeLoggingPreconditions", | ||
"StrictUnusedVariable", | ||
"StringBuilderConstantParameters", | ||
"ThrowError", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm a little worried promoting this straight away may lead to unexpected/unintended code rewriting - could we do a trial run on a few repos first? |
||
|
||
// Built-in checks | ||
"ArrayEquals", | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So we actually set
-XX:+CrashOnOutOfMemoryError
to try and avoid people trying to catch these and leaving their service in a weird state - shall we use another example (like NoSuchMethodError / NoClassDefFoundError)?https://github.com/palantir/sls-packaging/blob/develop/gradle-sls-packaging/src/main/groovy/com/palantir/gradle/dist/service/tasks/LaunchConfigTask.java#L59
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure thing -- note that there are some types of ooms that do not actually trigger crash-on-oom (iirc direct memory ooms)