gpt4 book ai didi

java - 最佳实践 : catching failure points in java.net.URL

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:02:10 26 4
gpt4 key购买 nike

JVM 新手,使用 Scala 和 Play 2.0

我正在将一个遗留应用程序转换为 Play,一个需要通过 Authorize.net 进行支付处理的应用程序。查看 java.net.URL 源代码,有许多潜在的失败点。鉴于我在下面编写的接口(interface),您将在哪里实现 try/catch block ?我需要相应地调整方法签名,可能会返回一个 Either[Error, Success] 来调用客户端代码

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 的调用者。在那里,您可以根据异常的种类提供不同的处理。

关于java - 最佳实践 : catching failure points in java.net.URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10848248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com