如何捕获 java 类的特定成员变量的 NullPointerException

问题描述 投票:0回答:1

我有一个名为

register
的方法,它采用自定义类(称为
RegistrationRequest
)作为参数,并且
RegistrationRequest
中有一些必需的变量,并且不能为 null(
url
type
)。
register
方法将注册保存在 DynamoDB 中。但是,如果两个必需变量中的任何一个为 null,我希望捕获自定义异常,并避免在 DynamoDB 中保存此类条目。这个方法的代码块有点像这样

public Registration register(RegistrationRequest registration)
var dbEntry = RegistrationImpl.builder()
            .withType(registration.getType())
            .withDescription(registration.getDescription())
            .withUrl(registration.getUrl())
            .withCategory(registration.getCategory())
            .withMaxDuration(registration.getMaxDuration())
            .build();
    try {
      return repository.save(dbEntry);
    }
    catch (Exception e) {
      ......
    }
 

我想要另一个 catch 块来检查

registration.type
registration.url
是否不为空,如果它们为空,则捕获它并引发异常,从而防止在 DynamoDB 中保存此类条目。我该怎么做?

java spring-boot nullpointerexception
1个回答
0
投票

输入方法即可进行验证。像这样的东西:

public Registration register(RegistrationRequest registration)
    if (registration.getType() == null || registration.getUrl() == null) {
        throw new CustomIllegalArgumentException(); // Or just log the error you want
    }
© www.soinside.com 2019 - 2024. All rights reserved.