google / google/gson

SocketExceptions being thrown as JsonSyntaxException in `fromJson`

Open
#1,717 4 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

I'm using the Gson's `fromJson` function with a `JsonReader` which uses the Socket input stream as it's source. When the socket is closed the `fromJson` function throws a `JsonSyntaxException` wrapping the underlying `SocketException`. When parsing the JSON I'd like to handle syntax problems separately from the `SocketException` (close the reader when the socket is closed/reset). I devised this ugly workaround for it (Kotlin code, but the same in Java):
```kotlin
try {
// fromJson call
} catch (e: JsonSyntaxException) {
if(e.cause is SocketException) {
throw e.cause as SocketException // unwrap the SocketException
}
// Handle syntax exception
} catch (e: JsonParseException) {
// Handle parse exception
}
```

The source shows a TODO comment where the exception is wrapped:
> // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException

I think it is not right to rethrow it as `JsonSyntaxException`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.