I am writing a web app where exceptions are used to handle error cases. Often, I find myself writing helpers like this:
def someHelper(...) : Boolean {...}
and then using it like this:
if (!someHelper(...)){
throw new SomeException()
}
These exceptions represent things like invalid parameters, and when handled they send a useful error message to the user, eg
try {
...
} catch {
case e: SomeException => "Bad user!"
}
Is this a reasonable approach? And how could I pass the exception into the helper function and have it thrown there? I have had trouble constructing a type for such a function.
I use
Eithermost of the time, not exceptions. I generally use exceptions, as you have done or some similar way, when the control flow has to go way, way back to some distant point, and otherwise there’s nothing sensible to do. However, when the exceptions can be handled fairly locally, I will insteadand then when I call this method, I can
or match on
Left(err)vsRight(form), or various other things.If I don’t want to handle the error right there, but instead want to process the return value, I
and I’ll get an
Eitherwith the error message unchanged as aLeft, if it was an error message, or with the result of{ foo(form); bar(form) }as aRightif it was okay. You can also chain your error processing usingflatMap, e.g. if you wanted to perform an additional check on so-far-correct values and reject some of them, you couldIt’s this sort of processing that makes using
Eithermore convenient (and usually better-performing, if exceptions are common) than exceptions, which is why I use them.(In fact, in very many cases I don’t care why something went wrong, only that it went wrong, in which case I just use an
Option.)