Exception handling (and error handling in general) is currently hard to do in AssemblyScript, because the developers are waiting for the WebAssembly exception proposal to go through.
The assemblyscript-json
package is recommended by the documentation, but it seems, at least to me from afar, to be unmaintained actively. Maybe the json-as
package would prove to be useful for you. Still no exception handling, but it does not fail on invalid jsons, it merely returns an object with all nulls and zeros, so you can check it more easily.
import { JSON } from "json-as";
export function test(): Player {
// @ts-ignore
const data: Player = {
firstName: "Emmet",
lastName: "West",
lastActive: [8, 27, 2022],
age: 23,
pos: {
x: -3.4,
y: 1.2
},
isVerified: true
}
return JSON.parse<Player>("[1, 2, 3]"); // invalid json
}
This, for me, returns:
{
firstName: null,
lastName: null,
lastActive: null,
age: 0,
pos: null,
isVerified: false
}
In order to install the package, be sure to call:
npm install --save json-as
because that is the name on the npm, as opposed to the name on github. You can check the package documentation on github, to ensure that this is correct.