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

前端之家收集整理的这篇文章主要介绍了最佳做法:捕获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的调用者.在那里,您可以根据异常的类型提供不同的处理.

原文链接:https://www.f2er.com/java/124609.html

猜你在找的Java相关文章