I'm looking for a more generic answer to a question I can't seem to find anywhere on the internet. Imagine you have a pseudo-function like so:
function mapError(error: Error, details?: Record<string, any>): {
switch(error.constructor) {
case Foo:
return new Bar(*some detail.id here*)
case Baz:
return new Fizz(*some detail.age here*)
}
}
details can have anything in it, such as an id that couldn't be found, some invalid data pertaining to the error, whatever. The point is that details is optional, generic, and holds additional information for whatever error you are trying to map.
The question: what is the best way to handle an unknown dictionary-like object so that you can pull meaningful data out of it? For instance, some errors might need an id in their messages, while other might be looking for age or something. The point is that the code throwing the error would add the metadata it knows about, and then we would add it into the mapped error being thrown.
Perhaps this isn't even the right way to go about it, but I'm trying to find some generic solution to passing metadata around so that any error can have meaningful information to pass on to a user. However, typechecking keeps getting in the way, leading me to infinite branches and unmaintainable code. I would think there is a slick, scalable solution to this, but nothing I have looked up has been useful. Any help appreciated!