我的理解是scala.util.Try
包装抛出Try { ... }
块内的任何代码的异常。
这是一个包装NullPointerException的简单示例。
object TryDemo extends App {
import scala.util.{Failure, Success, Try}
def doSomething(i: Int): String = {
if (i > 50) {
println("going to throw NullPointerException at index " + i)
throw new NullPointerException("- Exception at index " + i)
}
else
"some-result"
}
val t: Try[String] = Try {
var x = 0
while (x < 100) {
doSomething(x)
x += 1
}
"result-" + x
}
val result: Option[String] = t match {
case Success(s) => println("success " + s); Some(s)
case Failure(f) => println("failure " + f.getMessage()); None
}
}
这将以下输出作为例外。
将在索引51处抛出NullPointerException
失败 - 索引51处的异常
但是,当我尝试执行以下操作时(使用无效的URL确保每次都失败)
import play.api.libs.ws._
val wsURL = "http://invalidurl:9000/something"
val wsres: Try[Future[Response]] = Try {
WS.url(wsURL).withRequestTimeout(200).withQueryString(("param", value)).get
}
抛出异常而不是获取包含在Try
内的错误。
任何人都可以解释为什么它在第一种情况下工作而不是在第二种情况下?
[info] java.net.ConnectException: http://invalidurl:9000/something
[info] at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:103)
[info] at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:427)
[info] at org.jboss.netty.channel.DefaultChannelFuture.addListener(DefaultChannelFuture.java:145)
[info] at com.ning.http.client.providers.netty.NettyAsyncHttpProvider.doConnect(NettyAsyncHttpProvider.java:1068)
[info] at com.ning.http.client.providers.netty.NettyAsyncHttpProvider.execute(NettyAsyncHttpProvider.java:890)
[info] at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:520)
[info] at play.api.libs.ws.WS$WSRequest.execute(WS.scala:177)
[info] at play.api.libs.ws.WS$WSRequestHolder.get(WS.scala:386)
[info] at controllers.geojson.GeoJsonTransfomer$$anonfun$9.apply(GeoJsonTransformer.scala:155)
[info] at controllers.geojson.GeoJsonTransfomer$$anonfun$9.apply(GeoJsonTransformer.scala:155)
[info] ...
[info] Cause: java.nio.channels.UnresolvedAddressException:
[info] at sun.nio.ch.Net.checkAddress(Net.java:127)
[info] at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:640)
[info] at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink.connect(NioClientSocketPipelineSink.java:108)
[info] at org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink.eventSunk(NioClientSocketPipelineSink.java:70)
[info] at org.jboss.netty.handler.codec.oneone.OneToOneEncoder.handleDownstream(OneToOneEncoder.java:54)
[info] at org.jboss.netty.handler.codec.http.HttpClientCodec.handleDownstream(HttpClientCodec.java:97)
[info] at org.jboss.netty.handler.stream.ChunkedWriteHandler.handleDownstream(ChunkedWriteHandler.java:109)
[info] at org.jboss.netty.channel.Channels.connect(Channels.java:634)
[info] at org.jboss.netty.channel.AbstractChannel.connect(AbstractChannel.java:207)
[info] at org.jboss.netty.bootstrap.ClientBootstrap.connect(ClientBootstrap.java:229)