3 ms·
What does make people always think that the two things don't go together? In Scala I use Exceptions, but I don't throw them, I use monadic composition style. S
by valenterry 4y ago
What does make people always think that the two things don't go together?
In Scala I use Exceptions, but I don't throw them, I use monadic composition style. So I end up with clean code AND a stacktrace, just as if I had thrown them. Sometimes I wrap them for even easier debugging, e.g.
for {
user <- getUser
message <- getMessage
} yield showMessage(message, user)
And then when I call this function I do
renderMessage(x).mapError(e => RenderMessageError(message = x, cause = e))
Which, in case of an error, gives me a typical jvm stacktrace
Exception in thread "main" com.myproject.module.MyProjectFooBarException: Message x could not be rendered
at com.myproject.module.MyProject.anotherMethod(MyProject.java:19)
at com.myproject.module.MyProject.someMethod(MyProject.java:12)
at com.myproject.module.MyProject.main(MyProject.java:8)
Caused by: DatabaseError: User for ID ... not found
at org...(Fraction.java:143)
at com....(MyProject.java:17)
... 2 more
- tsimionescu 4y agoI'm not familiar with Scala or its integration with the JVM, but in Java at least, a stack trace is only collected for an exception from the moment it is thrown. If you create an exception object in one function, return it as a simple value, and then throw it from a new place, the stack trace will not show when the exception was created, only when it was thrown. This would mean that, in your example, if getUser were returning an error, the stack trace wouldn't show that, it would only point to the mapError() function. Is this correct, or does Scala actually integrate with the JVM such that it can show the original source of the error?
- valenterry 4y agoI don't think what you say is correct. See: https://stackoverflow.com/questions/69065097/why-java-stack-traces-are-generated-when-exceptions-are-constructed https://stackoverflow.com/questions/69065097/why-java-stack-... Hence it works in Scala (and also Java) without throwing Edit: maybe what you meant to say is that the stack is only unwinded at the time of generating the stacktrace and not when the exception is created? Which is true and a good thing since it's expensive to create it.
- tsimionescu 4y agoYou're right, andy impression was wrong. Thanks for finding out the correct info!