|
1 | 1 | package com.squareup.workflow1.traceviewer.util
|
2 | 2 |
|
3 | 3 | import com.squareup.moshi.JsonAdapter
|
4 |
| -import com.squareup.moshi.JsonDataException |
5 | 4 | import com.squareup.moshi.Moshi
|
6 | 5 | import com.squareup.moshi.Types
|
7 | 6 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
8 | 7 | import com.squareup.workflow1.traceviewer.model.Node
|
9 | 8 | import io.github.vinceglb.filekit.PlatformFile
|
10 | 9 | import io.github.vinceglb.filekit.readString
|
11 |
| -import java.io.IOException |
12 | 10 |
|
13 | 11 | /**
|
14 |
| - * Parses a given file's JSON String into [Node] with Moshi adapters. Moshi automatically throws JsonDataException |
15 |
| - * and IOException |
16 |
| - * @throws JsonDataException malformed JSON data or an error reading. |
17 |
| - * @throws IOException JSON is correct, but mismatch between class and JSON structure. |
| 12 | + * Parses a given file's JSON String into [Node] with Moshi adapters. |
| 13 | + * |
| 14 | + * @return A [ParseResult] representing result of parsing, either an error related to the |
| 15 | + * format of the JSON, or a success and a parsed trace. |
18 | 16 | */
|
19 | 17 | public suspend fun parseTrace(
|
20 | 18 | file: PlatformFile,
|
21 |
| -): List<Node> { |
22 |
| - val jsonString = file.readString() |
23 |
| - |
24 |
| - val moshi = Moshi.Builder() |
25 |
| - .add(KotlinJsonAdapterFactory()) |
26 |
| - .build() |
27 |
| - |
28 |
| - val workflowList = Types.newParameterizedType(List::class.java, Node::class.java) |
29 |
| - val workflowAdapter: JsonAdapter<List<Node>> = moshi.adapter(workflowList) |
30 |
| - val trace = workflowAdapter.fromJson(jsonString) |
31 |
| - if (trace == null) { |
32 |
| - throw JsonDataException("Could not parse JSON") |
| 19 | +): ParseResult { |
| 20 | + return try { |
| 21 | + val jsonString = file.readString() |
| 22 | + val moshi = Moshi.Builder() |
| 23 | + .add(KotlinJsonAdapterFactory()) |
| 24 | + .build() |
| 25 | + val workflowList = Types.newParameterizedType(List::class.java, Node::class.java) |
| 26 | + val workflowAdapter: JsonAdapter<List<Node>> = moshi.adapter(workflowList) |
| 27 | + val trace = workflowAdapter.fromJson(jsonString) |
| 28 | + ParseResult.Success(trace) |
| 29 | + } catch (e: Exception) { |
| 30 | + ParseResult.Failure(e) |
33 | 31 | }
|
34 |
| - return trace |
| 32 | +} |
| 33 | + |
| 34 | +sealed interface ParseResult { |
| 35 | + class Success(val trace: List<Node>?) : ParseResult |
| 36 | + class Failure(val error: Throwable) : ParseResult |
35 | 37 | }
|
0 commit comments