mirror of
https://github.com/lightbend/config.git
synced 2025-03-30 22:20:38 +08:00
README: recommend hasPath rather than catching Missing
This commit is contained in:
parent
0a7db6a126
commit
5038949cff
12
README.md
12
README.md
@ -306,10 +306,13 @@ options:
|
||||
|
||||
1. Set it in a `reference.conf` included in your library or
|
||||
application jar, so there's a default value.
|
||||
2. Catch and handle `ConfigException.Missing`.
|
||||
3. Use the `Config.hasPath()` method to check in advance whether
|
||||
2. Use the `Config.hasPath()` method to check in advance whether
|
||||
the path exists (rather than checking for `null`/`None` after as
|
||||
you might in other APIs).
|
||||
3. Catch and handle `ConfigException.Missing`. NOTE: using an
|
||||
exception for control flow like this is much slower than using
|
||||
`Config.hasPath()`; the JVM has to do a lot of work to throw
|
||||
an exception.
|
||||
4. In your initialization code, generate a `Config` with your
|
||||
defaults in it (using something like `ConfigFactory.parseMap()`)
|
||||
then fold that default config into your loaded config using
|
||||
@ -341,10 +344,9 @@ like this to use the idiomatic `Option` syntax:
|
||||
|
||||
```scala
|
||||
implicit class RichConfig(val underlying: Config) extends AnyVal {
|
||||
def getOptionalBoolean(path: String): Option[Boolean] = try {
|
||||
def getOptionalBoolean(path: String): Option[Boolean] = if (underlying.hasPath(path)) {
|
||||
Some(underlying.getBoolean(path))
|
||||
} catch {
|
||||
case e: ConfigException.Missing =>
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user