I have the following method that deals with multiple streams and I now want to add exception handling in a functional style. Any suggestions?
private def convertToByte(json: String): Array[Byte] = {
val bytes= json.getBytes("UTF-8")
val bin: ByteArrayInputStream = new ByteArrayInputStream(bytes)
val bos: ByteArrayOutputStream = new ByteArrayOutputStream()
val gzip: GZIPOutputStream = new GZIPOutputStream(bos)
val buff = new Array[Byte](1024)
var len = bin.read(buff)
while(len != -1)
{
gzip.write(buff, 0, len)
len = bin.read(buff)
}
gzip.finish()
bin.close()
bos.close()
gzip.close()
bos.toByteArray
}
I want to wrap all the calls to close in a finally block and at the same time, in case of an exception, I want to catch that and return the error message as a byte array. Having worked with Java, my hand automatically goes the imperative way to wrap the piece of code in a try catch finally, but I'm thinking of writing it in a functional way by wrapping that in a higher order function. But I'm stuck getting started. Any pointers?