我将遗留应用程序转换为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.jb51.cc/java/124609.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。