In this post under DotEnv I will show with example what is the purpose of “ignoreIfMalformed” method with an example.
If the “.env” is not properly formed i.e., if there is syntax error. The default behavior of DotEnv framework is to thrown an exception.
We can change this default behavior.
We can configure DotEnv to not throw an exception even if the file is malformed.
That is where “ignoreIfMalformed” method comes into picture.
Calling this method configures the “DotEnv” instance to not throw exception if the environment file is malformed.
For our example lets have file named “malformed-file.env” with below data
CUSTOM_FILE_MY_ENV_VAR1=some_value1
CUSTOM_FILE_MY_ENV_VAR2*************
Below is the main class that shows how to configure “DotEnv” instance to not throw an exception if the environment file is malformed.
Main class
package defaultPackage;
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;
public class Example9 {
public static void main(String[] args) {
try {
Dotenv dotenv = Dotenv.configure().filename("malformed-file.env").load();
System.out.println("First Attempt: Exception not thrown");
}catch (DotenvException dotenvException) {
System.out.println("First Attempt: Exception thrown");
}
try {
Dotenv dotenv = Dotenv.configure().filename("malformed-file.env").ignoreIfMalformed().load();
System.out.println("Second Attempt: Exception not thrown");
System.out.println("Value of 'CUSTOM_FILE_MY_ENV_VAR1': " + dotenv.get("CUSTOM_FILE_MY_ENV_VAR1"));
System.out.println("Value of 'CUSTOM_FILE_MY_ENV_VAR2': " + dotenv.get("CUSTOM_FILE_MY_ENV_VAR2"));
} catch(DotenvException dotenvException) {
System.out.println("Second Attempt: Exception thrown");
}
}
}
In the above code, in the first attempt we are trying to load the malformed env file and we get an exception.
This exception is caught and print to console as “First Attempt: Exception thrown”
In the second attempt we are configuring the “Dotenv” to not throw an exception, when we try to load malformed env file, by calling “ignoreIfMalformed” method at line 16.
Now the malformed env file is opened, exception is not thrown, print the value of “CUSTOM_FILE_MY_ENV_VAR1”, whereas for “CUSTOM_FILE_MY_ENV_VAR2” it will print null.
In this way, we can configure Dotenv to not throw an exception when reading malformed env file.
Below is the output for your reference
Output
First Attempt: Exception thrown
Second Attempt: Exception not thrown
Value of 'CUSTOM_FILE_MY_ENV_VAR1': some_value1
Value of 'CUSTOM_FILE_MY_ENV_VAR2': null