Should Error be `instanceof Error`?
Catching RPC errors in TypeScript is a little hard. Usually you'd want to use instanceof Error to access its message property. We had an issue with this in Delta Chat: https://github.com/deltachat/deltachat-desktop/pull/5008.
I'd suggest to define a class
class JSONRPCError extends Error {
constructor(errObj) {
super(errObj.message);
this.code = errObj.code;
this.data = errObj.data;
}
}
However, this might be breaking because
JSON.stringify(new JSONRPCError({ code: -1, data: { a: 1 }, message: 'some error' }))
=== '{"code":-1,"data":{"a":1}}'
, i.e. message is missing. OTOH
console.log(`${new JSONRPCError({ code: -1, data: { a: 1 }, message: 'some error' })}`)
prints Error: some error, i.e. the other properties are missing.
For reference, here is how others do it: https://github.com/open-rpc/client-js/pull/234/files
I found another advantage of this. It's that you can get the stack trace regardless of where you receive the error object. This could be inside of window.addEventListener('unhandledrejection', which is what we have in Delta Chat Desktop. Otherwise you can only see the error message and code, but not where the promise has been created.
https://stackoverflow.com/questions/43834559/how-to-find-which-promises-are-unhandled-in-node-js-unhandledpromiserejectionwar/55192652#55192652