debugMinor
Cleaning up file resources in a DRY manner
Viewed 0 times
filemannerdryresourcescleaning
Problem
I've written a function that generates a report, and then sends it as an attachment to an email. I don't want to clutter the function with a lot of calls to close up the filesystem, if there was an error along the way. What do you all think?
Assume that throwing exceptions is a legitimate design choice for this function, the calling process expects exceptions to be thrown and handles them gracefully.
// attempt to generate the report, any error will be wrapped in Failure(ex)
val op1 = Try {
DB.withConnection{ implicit c =>
generateReport(command.programId, token.claims)(output, c)
}
}
// use (abuse?) pattern matching to send the report if it generated succesfully
val op2 = op1 match {
case Success(_) => Try(sendReport(Address(user.email, user.first), file, command.created))
// if the op1 value is of type Failure(ex), carry it forward until after the temp files have been removed
case Failure(ex) => Failure(ex)
}
// the operations have either succeeded or failed, so clean up the filesystem
cleanUp(output, file)
// throw any exception that occurred along the way
op2.getAssume that throwing exceptions is a legitimate design choice for this function, the calling process expects exceptions to be thrown and handles them gracefully.
Solution
I think this can be written more cleanly with
Returns the given function applied to the value from this
flatMapflatMapU ⇒ Try[U]): Try[U]Returns the given function applied to the value from this
Success or returns this if this is a Failure.val isReportSent = Try {
...
}.flatMap(_ => Try { sendReport(...) })
cleanUp(output, file)
isReportSent.getCode Snippets
val isReportSent = Try {
...
}.flatMap(_ => Try { sendReport(...) })
cleanUp(output, file)
isReportSent.getContext
StackExchange Code Review Q#61917, answer score: 3
Revisions (0)
No revisions yet.