-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdecoding.ts
More file actions
23 lines (19 loc) · 695 Bytes
/
Copy pathdecoding.ts
File metadata and controls
23 lines (19 loc) · 695 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import * as td from "tiny-decoders";
export class DecodingError extends Error {
public constructor(error: td.DecoderError, context: string, dataIsSensitive: boolean) {
super(`Unexpected data in ${context}: ${td.format(error, { sensitive: dataIsSensitive })}`);
this.name = "DecodingError";
}
}
export function decodeOrThrow<T>(namedParameters: {
codec: td.Codec<T>,
data: unknown,
context: string,
dataIsSensitive: boolean,
}): T {
const result = namedParameters.codec.decoder(namedParameters.data);
if (result.tag === "DecoderError") {
throw new DecodingError(result.error, namedParameters.context, namedParameters.dataIsSensitive);
}
return result.value;
}