将变量传递给异常

huangapple go评论66阅读模式
英文:

Passing variable to an exception

问题

I have translated the code portion for you:

private static void ignoringExc(RunnableExc r) {
    try {
        r.run();
    } catch (Exception e) {
        log.error("The age of Person B is null");
    }
}

@FunctionalInterface
private interface RunnableExc {
    void run() throws Exception;
}

Please note that I have customized the error message in the log.error() call to say "The age of Person B is null."

英文:
	private static void ignoringExc(RunnableExc r) {
		try {
			r.run();
		} catch (Exception e) {
			log.error("");
		}
	}

	@FunctionalInterface
	private interface RunnableExc {
		void run() throws Exception;
	}

I have multiple variables that need to be set into a Person a. However, some variables from Person b may be null. So I use the above function to avoid null pointer exception error. But I want to customise the error message in log.error() in ignoringExc function, such as "The age of Person B is null". How to do that?

ignoringExc(() -> a.setAddress(b.getPerson("address")));
ignoringExc(() -> a.setName(b.getPerson("name")));
ignoringExc(() -> a.setAge(b.getPerson("age")));
...

答案1

得分: 4

不应该使用 NullPointerException 来进行空值检查。抛出异常相对昂贵,正如 @user16320675 指出的,可能会发生其他 NPE,并且您还捕获了 Exception,这将忽略其他问题。

而是使用以下函数:

static <T> void setIfNotNull(T value, Consumer<T> setter) {
    if (value != null) {
        setter.accept(value);
    } else {
        // 如果需要的话,记录日志
    }
}

然后像这样调用它:

setIfNotNull(b.getName(), a::setName);

当然,您还可以考虑让 A 上的设置器静默忽略 null,而不是抛出异常,但这取决于您的要求。

英文:

You shouldn't be using NullPointerException to do null checks. Throwing an exception is relatively expensive, as @user16320675 points out, other NPE's may occur, and you are also catching Exception which will ignore other problems.

Instead, use a function like:

    static &lt;T&gt; void setIfNotNull(T value, Consumer&lt;T&gt; setter) {
        if (value != null) {
            setter.accept(value);
        } else {
            // logging if needed
        }
    }

and call it like this:

        setIfNotNull(b.getName(), a::setName);

Of course you could also consider making the setters on A silently ignore null instead of throwing an exception, but that depends on your requirements.

答案2

得分: 1

You could pass in a String as well. This is common practice for some of the precondition tools in Java. Take a look at Objects#requireNonNull(T) vs Objects#requireNonNull(T,String).

So, like this.

    private static void ignoringExc(RunnableExc r, String message) {
        try {
            r.run();
        } catch (Exception e) {
            log.error(message);
        }
    }

    @FunctionalInterface
    private interface RunnableExc {
        void run() throws Exception;
    }

Which would then allow you to do this.

ignoringExc(() -&gt; a.setAddress(b.getPerson(&quot;address&quot;)), &quot;address message&quot;);
ignoringExc(() -&gt; a.setName(b.getPerson(&quot;name&quot;)),       &quot;name message&quot;);
ignoringExc(() -&gt; a.setAge(b.getPerson(&quot;age&quot;)),         &quot;age message&quot;);
...
英文:

You could pass in a String as well. This is common practice for some of the precondition tools in Java. Take a look at Objects#requireNonNull(T) vs Objects#requireNonNull(T,String).

So, like this.

    private static void ignoringExc(RunnableExc r, String message) {
        try {
            r.run();
        } catch (Exception e) {
            log.error(message);
        }
    }

    @FunctionalInterface
    private interface RunnableExc {
        void run() throws Exception;
    }

Which would then allow you to do this.

ignoringExc(() -&gt; a.setAddress(b.getPerson(&quot;address&quot;)), &quot;address message&quot;);
ignoringExc(() -&gt; a.setName(b.getPerson(&quot;name&quot;)),       &quot;name message&quot;);
ignoringExc(() -&gt; a.setAge(b.getPerson(&quot;age&quot;)),         &quot;age message&quot;);
...

huangapple
  • 本文由 发表于 2023年5月18日 12:14:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定