Best practice: capture Java net. Failure point in URL
New features of JVM using Scala and play 2.0
I convert the legacy application to play through authorize Net for payment processing Through Java net. URL source code, there are many potential failure points Given the interface I wrote below, where will you implement the try / catch block? I need to adjust the method signature accordingly and may return an [error, success] to the calling client code
import java.net.{URL,URLEncoder} import java.io.{BufferedReader,DataOutputStream,InputStreamReader} import javax.net.ssl._ trait Authnet { private val prodUrl = "https://secure.authorize.net/gateway/transact.dll" private val testUrl = "https://test.authorize.net/gateway/transact.dll" protected def authNetProcess(params: Map[String,String]) = { val(conn,urlParams) = connect(params) val request = new DataOutputStream( conn.getOutputStream ) request.write(urlParams.getBytes) request.flush() request.close() val response = new BufferedReader(new InputStreamReader(conn.getInputStream)) val results = response.readLine().split("\\|") response.close() results.toList } private def connect(params: Map[String,String]) = { val urlParams = (config ++ params) map { case(k,v) => URLEncoder.encode(k,"UTF-8") + "=" + URLEncoder.encode(v,"UTF-8") } mkString("&") lazy val url = if (isDev) new URL(testUrl) else new URL(prodUrl) val conn = url.openConnection conn.setDoOutput(true) conn.setUseCaches(false) (conn,urlParams) } private val config = Map( 'x_login -> "...",'x_tran_key -> "...",... ) }
Solution
Stick to the thumb rule:
There is no clear definition of "must handle", but this means that you should resist the impulse of an exception, because you can only throw one exception
"Must handle" is mainly defined by how the application should work or other dependencies
In this case, grasping this point also adds some meaningful processing
I always question the added value of replacing an exception with another exception
Apply it to your example:
No, There is no way to handle this exception in connect() So it can leave the exception to the caller of authnetprocess There, you can provide different handling according to the type of exception