最佳做法:捕获java.net.URL中的失败点

使用 Scala和Play 2.0进行JVM的新功能

我将遗留应用程序转换为Play,需要通过Authorize.net进行付款处理.通过java.net.URL源码,有许多潜在的失败点.给出我在下面写的接口,你将在哪里实现try / catch块?我需要相应地调整方法签名,可能返回一个[错误,成功]到调用客户端代码

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     -> "...",...
  )
}

解决方法

坚持拇指规则:

Only catch an exception if you must handle it.

“必须处理”没有清晰的定义,但这意味着你应该抵制一个异常的冲动,因为你只能抛出一个异常.

“必须处理”主要由应用程序应该如何工作或其他依赖关系定义.

If the application requires to display an error to the user instead of aborting with an exception,then it’s a must.

在这种情况下,抓住这一点也增加了一些有意义的处理.

If an API requires to throw a different exception,then it’s a must,but the APIs deFinition is possibly not sound.

我总是质疑用另外一个异常替换异常的附加值.

将其应用于您的示例:

Would it add some value to catch an exception from connect() in authNetProcess()?

没有!没有办法在connect()中处理这个异常.所以它可以将该异常留给authNetProcess的调用者.在那里,您可以根据异常的类型提供不同的处理.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...