1
0
mirror of https://github.com/square/okhttp.git synced 2025-08-07 12:42:57 +03:00

Use check/require instead of if/throw

This commit is contained in:
Jesse Wilson
2019-05-20 18:08:58 -04:00
parent 0718352c4e
commit 2c59337e31
10 changed files with 30 additions and 52 deletions

View File

@@ -513,9 +513,7 @@ class MockWebServer : ExternalResource(), Closeable {
val sink = raw.sink().buffer() val sink = raw.sink().buffer()
while (true) { while (true) {
val socketPolicy = dispatcher.peek().getSocketPolicy() val socketPolicy = dispatcher.peek().getSocketPolicy()
if (!processOneRequest(raw, source, sink)) { check(processOneRequest(raw, source, sink)) { "Tunnel without any CONNECT!" }
throw IllegalStateException("Tunnel without any CONNECT!")
}
if (socketPolicy === UPGRADE_TO_SSL_AT_END) return if (socketPolicy === UPGRADE_TO_SSL_AT_END) return
} }
} }
@@ -676,8 +674,8 @@ class MockWebServer : ExternalResource(), Closeable {
} }
val method = request.substringBefore(' ') val method = request.substringBefore(' ')
if (hasBody && !HttpMethod.permitsRequestBody(method)) { require(!hasBody || HttpMethod.permitsRequestBody(method)) {
throw IllegalArgumentException("Request must not have a body: $request") "Request must not have a body: $request"
} }
return RecordedRequest(request, headers.build(), chunkSizes, requestBody.receivedByteCount, return RecordedRequest(request, headers.build(), chunkSizes, requestBody.receivedByteCount,

View File

@@ -47,9 +47,7 @@ object DnsRecordCodec {
val labels = host.split('.').dropLastWhile { it.isEmpty() } val labels = host.split('.').dropLastWhile { it.isEmpty() }
for (label in labels) { for (label in labels) {
val utf8ByteCount = label.utf8Size() val utf8ByteCount = label.utf8Size()
if (utf8ByteCount != label.length.toLong()) { require(utf8ByteCount == label.length.toLong()) { "non-ascii hostname: $host" }
throw IllegalArgumentException("non-ascii hostname: $host")
}
nameBuf.writeByte(utf8ByteCount.toInt()) nameBuf.writeByte(utf8ByteCount.toInt())
nameBuf.writeUtf8(label) nameBuf.writeUtf8(label)
} }
@@ -69,9 +67,7 @@ object DnsRecordCodec {
buf.readShort() // query id buf.readShort() // query id
val flags = buf.readShort().toInt() and 0xffff val flags = buf.readShort().toInt() and 0xffff
if (flags shr 15 == 0) { require(flags shr 15 != 0) { "not a response" }
throw IllegalArgumentException("not a response")
}
val responseCode = flags and 0xf val responseCode = flags and 0xf

View File

@@ -352,7 +352,7 @@ class Cache internal constructor(
} }
override fun remove() { override fun remove() {
if (!canRemove) throw IllegalStateException("remove() before next()") check(canRemove) { "remove() before next()" }
delegate.remove() delegate.remove()
} }
} }

View File

@@ -193,7 +193,7 @@ class CacheControl private constructor(
* precision; finer precision will be lost. * precision; finer precision will be lost.
*/ */
fun maxAge(maxAge: Int, timeUnit: TimeUnit) = apply { fun maxAge(maxAge: Int, timeUnit: TimeUnit) = apply {
if (maxAge < 0) throw IllegalArgumentException("maxAge < 0: $maxAge") require(maxAge >= 0) { "maxAge < 0: $maxAge" }
val maxAgeSecondsLong = timeUnit.toSeconds(maxAge.toLong()) val maxAgeSecondsLong = timeUnit.toSeconds(maxAge.toLong())
this.maxAgeSeconds = maxAgeSecondsLong.clampToInt() this.maxAgeSeconds = maxAgeSecondsLong.clampToInt()
} }
@@ -206,7 +206,7 @@ class CacheControl private constructor(
* [TimeUnit.SECONDS] precision; finer precision will be lost. * [TimeUnit.SECONDS] precision; finer precision will be lost.
*/ */
fun maxStale(maxStale: Int, timeUnit: TimeUnit) = apply { fun maxStale(maxStale: Int, timeUnit: TimeUnit) = apply {
if (maxStale < 0) throw IllegalArgumentException("maxStale < 0: $maxStale") require(maxStale >= 0) { "maxStale < 0: $maxStale" }
val maxStaleSecondsLong = timeUnit.toSeconds(maxStale.toLong()) val maxStaleSecondsLong = timeUnit.toSeconds(maxStale.toLong())
this.maxStaleSeconds = maxStaleSecondsLong.clampToInt() this.maxStaleSeconds = maxStaleSecondsLong.clampToInt()
} }
@@ -220,7 +220,7 @@ class CacheControl private constructor(
* [TimeUnit.SECONDS] precision; finer precision will be lost. * [TimeUnit.SECONDS] precision; finer precision will be lost.
*/ */
fun minFresh(minFresh: Int, timeUnit: TimeUnit) = apply { fun minFresh(minFresh: Int, timeUnit: TimeUnit) = apply {
if (minFresh < 0) throw IllegalArgumentException("minFresh < 0: $minFresh") require(minFresh >= 0) { "minFresh < 0: $minFresh" }
val minFreshSecondsLong = timeUnit.toSeconds(minFresh.toLong()) val minFreshSecondsLong = timeUnit.toSeconds(minFresh.toLong())
this.minFreshSeconds = minFreshSecondsLong.clampToInt() this.minFreshSeconds = minFreshSecondsLong.clampToInt()
} }

View File

@@ -877,7 +877,7 @@ class HttpUrl internal constructor(
} }
fun port(port: Int): Builder { fun port(port: Int): Builder {
if (port <= 0 || port > 65535) throw IllegalArgumentException("unexpected port: $port") require(port in 1..65535) { "unexpected port: $port" }
this.port = port this.port = port
return this return this
} }
@@ -926,8 +926,8 @@ class HttpUrl internal constructor(
fun setPathSegment(index: Int, pathSegment: String): Builder { fun setPathSegment(index: Int, pathSegment: String): Builder {
val canonicalPathSegment = pathSegment.canonicalize(encodeSet = PATH_SEGMENT_ENCODE_SET) val canonicalPathSegment = pathSegment.canonicalize(encodeSet = PATH_SEGMENT_ENCODE_SET)
if (isDot(canonicalPathSegment) || isDotDot(canonicalPathSegment)) { require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) {
throw IllegalArgumentException("unexpected path segment: $pathSegment") "unexpected path segment: $pathSegment"
} }
encodedPathSegments[index] = canonicalPathSegment encodedPathSegments[index] = canonicalPathSegment
return this return this
@@ -939,8 +939,8 @@ class HttpUrl internal constructor(
alreadyEncoded = true alreadyEncoded = true
) )
encodedPathSegments[index] = canonicalPathSegment encodedPathSegments[index] = canonicalPathSegment
if (isDot(canonicalPathSegment) || isDotDot(canonicalPathSegment)) { require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) {
throw IllegalArgumentException("unexpected path segment: $encodedPathSegment") "unexpected path segment: $encodedPathSegment"
} }
return this return this
} }
@@ -954,9 +954,7 @@ class HttpUrl internal constructor(
} }
fun encodedPath(encodedPath: String): Builder { fun encodedPath(encodedPath: String): Builder {
if (!encodedPath.startsWith("/")) { require(encodedPath.startsWith("/")) { "unexpected encodedPath: $encodedPath" }
throw IllegalArgumentException("unexpected encodedPath: $encodedPath")
}
resolvePath(encodedPath, 0, encodedPath.length) resolvePath(encodedPath, 0, encodedPath.length)
return this return this
} }

View File

@@ -17,16 +17,16 @@ package okhttp3
import okhttp3.Protocol.HTTP_1_1 import okhttp3.Protocol.HTTP_1_1
import okhttp3.Protocol.HTTP_2 import okhttp3.Protocol.HTTP_2
import okhttp3.internal.checkDuration
import okhttp3.internal.cache.InternalCache import okhttp3.internal.cache.InternalCache
import okhttp3.internal.checkDuration
import okhttp3.internal.eventListenerFactory import okhttp3.internal.eventListenerFactory
import okhttp3.internal.toImmutableList
import okhttp3.internal.immutableListOf import okhttp3.internal.immutableListOf
import okhttp3.internal.platform.Platform import okhttp3.internal.platform.Platform
import okhttp3.internal.platformTrustManager import okhttp3.internal.platformTrustManager
import okhttp3.internal.proxy.NullProxySelector import okhttp3.internal.proxy.NullProxySelector
import okhttp3.internal.tls.CertificateChainCleaner import okhttp3.internal.tls.CertificateChainCleaner
import okhttp3.internal.tls.OkHostnameVerifier import okhttp3.internal.tls.OkHostnameVerifier
import okhttp3.internal.toImmutableList
import okhttp3.internal.ws.RealWebSocket import okhttp3.internal.ws.RealWebSocket
import okio.Sink import okio.Sink
import okio.Source import okio.Source
@@ -531,9 +531,7 @@ open class OkHttpClient internal constructor(
* If unset, the [system-wide default][SocketFactory.getDefault] socket factory will be used. * If unset, the [system-wide default][SocketFactory.getDefault] socket factory will be used.
*/ */
fun socketFactory(socketFactory: SocketFactory) = apply { fun socketFactory(socketFactory: SocketFactory) = apply {
if (socketFactory is SSLSocketFactory) { require(socketFactory !is SSLSocketFactory) { "socketFactory instanceof SSLSocketFactory" }
throw IllegalArgumentException("socketFactory instanceof SSLSocketFactory")
}
this.socketFactory = socketFactory this.socketFactory = socketFactory
} }

View File

@@ -77,10 +77,7 @@ class RealInterceptorChain(
fun transmitter(): Transmitter = transmitter fun transmitter(): Transmitter = transmitter
fun exchange(): Exchange { fun exchange(): Exchange = exchange!!
if (exchange == null) throw IllegalStateException()
return exchange
}
override fun call(): Call = call override fun call(): Call = call
@@ -97,15 +94,13 @@ class RealInterceptorChain(
calls++ calls++
// If we already have a stream, confirm that the incoming request will use it. // If we already have a stream, confirm that the incoming request will use it.
if (this.exchange != null && !this.exchange.connection()!!.supportsUrl(request.url())) { check(this.exchange == null || this.exchange.connection()!!.supportsUrl(request.url())) {
throw IllegalStateException("network interceptor " + interceptors[index - 1] + "network interceptor ${interceptors[index - 1]} must retain the same host and port"
" must retain the same host and port")
} }
// If we already have a stream, confirm that this is the only call to chain.proceed(). // If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.exchange != null && calls > 1) { check(this.exchange == null || calls <= 1) {
throw IllegalStateException("network interceptor " + interceptors[index - 1] + "network interceptor ${interceptors[index - 1]} must call proceed() exactly once"
" must call proceed() exactly once")
} }
// Call the next interceptor in the chain. // Call the next interceptor in the chain.
@@ -118,15 +113,11 @@ class RealInterceptorChain(
"interceptor $interceptor returned null") "interceptor $interceptor returned null")
// Confirm that the next interceptor made its required call to chain.proceed(). // Confirm that the next interceptor made its required call to chain.proceed().
if (exchange != null && index + 1 < interceptors.size && next.calls != 1) { check(exchange == null || index + 1 >= interceptors.size || next.calls == 1) {
throw IllegalStateException("network interceptor " + interceptor + "network interceptor $interceptor must call proceed() exactly once"
" must call proceed() exactly once")
} }
if (response.body() == null) { check(response.body() != null) { "interceptor $interceptor returned a response with no body" }
throw IllegalStateException(
"interceptor $interceptor returned a response with no body")
}
return response return response
} }

View File

@@ -383,8 +383,8 @@ class Http1ExchangeCodec(
} }
override fun read(sink: Buffer, byteCount: Long): Long { override fun read(sink: Buffer, byteCount: Long): Long {
if (byteCount < 0L) throw IllegalArgumentException("byteCount < 0: $byteCount") require(byteCount >= 0L) { "byteCount < 0: $byteCount" }
if (closed) throw IllegalStateException("closed") check(!closed) { "closed" }
if (bytesRemaining == 0L) return -1 if (bytesRemaining == 0L) return -1
val read = super.read(sink, minOf(bytesRemaining, byteCount)) val read = super.read(sink, minOf(bytesRemaining, byteCount))

View File

@@ -393,8 +393,7 @@ class AndroidPlatform(
} catch (ignored: NoSuchMethodException) { } catch (ignored: NoSuchMethodException) {
} }
} }
throw IllegalStateException( throw IllegalStateException("Expected Android API level 21+ but was ${Build.VERSION.SDK_INT}")
"Expected Android API level 21+ but was " + Build.VERSION.SDK_INT)
} }
} }
} }

View File

@@ -131,9 +131,7 @@ object WebSocketProtocol {
fun validateCloseCode(code: Int) { fun validateCloseCode(code: Int) {
val message = closeCodeExceptionMessage(code) val message = closeCodeExceptionMessage(code)
if (message != null) { require(message == null) { message!! }
throw IllegalArgumentException(message)
}
} }
fun acceptHeader(key: String): String { fun acceptHeader(key: String): String {