yerpc icon indicating copy to clipboard operation
yerpc copied to clipboard

Should Error be `instanceof Error`?

Open WofWca opened this issue 8 months ago • 1 comments

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

WofWca avatar Apr 18 '25 10:04 WofWca

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

WofWca avatar Apr 29 '25 11:04 WofWca