I am trying to keep an app from launching if the dbHost isn’t supplied. The code below works, but the error is simply “Not found”. I don’t get the Error(message) I wrote.
Ideally, I just want to see the message “The environment variable for DB_HOST hasn’t been set”.
// Getting the dbHost environment variable
let nodeEnv = Node.Process.process["env"]
// Check if DB_HOST is available
let dbHostResult = switch Js.Dict.get(nodeEnv, "DB_HOST") {
| Some(value) => Ok(value)
| None => Error(`The environment variable for DB_HOST hasn't been set`)
}
let dbHost = Belt.Result.getExn(dbHostResult)
Js.log(dbHost)
Now after re-reading your question, I don’t understand the problem you are trying to solve.
Do you want to throw an exception, or access the Error case of a result?
If you just want to access the Error message of a result, you should prefer a switch over Belt.Result.getExn.
If you are interested in raising an actual exception, you’d go with @praveen’s approach… but then I don’t understand why you’d want to convert the previous option value into a result value first?
@ryyppy What I want to do is to read the “DB_HOST” from Node.process.process[“env”] and assign it to a variable dbHost, and if it doesn’t exist throw an exception with DB_HOST not found so the error thrown in the exception is understandable.
Just a final question on this topic. By using the try-catch the definition of the variable is only valid inside the try-catch block. How do I get it out?