#Handling optional function metadata

1 messages · Page 1 of 1 (latest)

pine ridge
#

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!

split turtle
#

This could give you a few ideas that you could incorporate: https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
Type predicates: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates will help you tell typescript what type you're dealing with. "If it has age attribute, then it is Person".

In operator: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing is also helpful, "if age key exists in this unknown object, I can include it in the message".

In general, the narrowing section should help you fight typechecking less.

TypeScript forces you to acknowledge you can't know what was thrown making getting the error message a pain. Here's how you can manage it.

pine ridge
#

Hmm that does give me some ideas, perhaps errors could pass specific types of messages that conform to an interface, and then in the mapping I could utilize narrowing to slim down who actually gets what piece of the message.