我必须验证包含大约 40 个必填字段的请求。
我想通过避免经典的 if (field1 == null) throw new XXException("msg");
例如我有以下代码:
if (caller == null)
{
// Caller cannot be empty
throw new CallerErrorException(new CallerError("", "incorrect caller"));
}
if (person == null)
{
// Person cannot be empty
throw new PersonErrorException(new CustomerError("", "incorrect customer"));
}
if (module == null)
{
// Module cannot be empty
throw new ModuleErrorException(new ModuleError("", "module must be X"));
}
如您所见,根据哪个字段为空,将抛出带有自定义消息的特定自定义异常。
所以,我想要这样的东西:
assertNotEquals(call, null, new CallerErrorException(new CallerError("", "incorrect caller")));
assertNotEquals(person, null, new PersonErrorException(new CustomerError("", "incorrect caller")));
assertNotEquals(module , null, new ModuleErrorException(new ModuleError("", "incorrect caller")));
是否有允许我执行此操作的内置功能?
我知道 assertEquals 会生成 assertionError,但我需要生成自定义异常。
最佳答案
没有内置的东西可以为此工作,但您当然可以编写自己的:
static void checkNull(Object val, Class exClass, Class innerClass, String arg1, String arg2)
throws Exception {
if (val != null) {
return;
}
Object inner = innerClass
.getDeclaredConstructor(String.class, String.class)
.newInstance(arg1, arg2);
throw (Exception)exClass
.getDeclaredConstructor(innerClass) // This may need to be changed
.newInstance(inner);
}
以上代码根据需要使用反射构建异常对象。如果它需要内部错误对象的父类(super class)来匹配正确的类型,您可能必须更改传递给异常对象的构造函数的类型。
现在您可以编写如下代码:
checkNull(caller, CallerErrorException.class, CallerError.class, "", "incorrect caller");
checkNull(person, PersonErrorException.class, PersonError.class, "", "incorrect person");
这种方法可以让您避免在不需要抛出异常对象的情况下创建异常对象。
关于java - 是否可以从 assert 方法引发自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195979/