【发布时间】:2021-10-28 09:51:54
【问题描述】:
我想知道 ArchUnit 中是否存在避免方法签名引发任何已检查异常的方法。
【问题讨论】:
标签: archunit
我想知道 ArchUnit 中是否存在避免方法签名引发任何已检查异常的方法。
【问题讨论】:
标签: archunit
您可以通过JavaMethod.getThrowsClause()(或JavaConstructor.getThrowsClause(),分别)访问代码单元声明的异常。
以下使用custom condition 的规则禁止声明任何异常——如果您想排除RuntimeExceptions,您可以轻松地根据需要调整它:
@ArchTest
static ArchRule no_code_units_should_declare_exceptions = noCodeUnits()
.should(new ArchCondition<JavaCodeUnit>("declare exceptions") {
@Override
public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
int nThrowsDeclarations = codeUnit.getThrowsClause().size();
String message = String.format("%s has %d throws declarations in %s",
codeUnit.getDescription(), nThrowsDeclarations, codeUnit.getSourceCodeLocation()
);
events.add(new SimpleConditionEvent(codeUnit, nThrowsDeclarations > 0, message));
}
});
【讨论】: