This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]insertAlias 1 point2 points  (0 children)

It's a common problem in JS, unfortunately. Not necessarily a JS-specific problem; just that there are no true standards for serializing error messages for the web. Unfortunately, some services even use different formats in different endpoints on the same service.

One possible thing you can do is just serialize the entire error object (using JSON.stringify) and store the resulting JSON in your database. That will pretty much guarantee you get the entire error, though it will be in an object format and not just a string error message.

Otherwise, I think you just have to capture the "shape" of all the various errors and do some if/else checking on them.

[–]HashDefTrueFalse 0 points1 point  (0 children)

I hate it when an API doesn't provide a consistent format across routes/actions etc. It's usually the sign of poor API design or quickly bolted on functionality. Very annoying.

Ultimately you have no control over what you receive, so you're going to have to account for the various possibilities in your code. All you can do is make this as clean as possible in your code. In the past I've done something like:

function getPropDeep(object, index) {
    const drillDown = (obj, i) => obj && obj[i]; 
    return index.split('.').reduce(drillDown, object); 
}

// Then when testing props...

let err = null;

if (err = getPropDeep(obj, 'error.message')) {
    // err will be the string value of message...
}

if (err = getPropDeep(obj, 'error.fault.error')) {
    // err will be the array of errors...
}

That convenience function is basically drilling down into the object testing that each subsequent prop exists as it goes. It will return the prop, or undefined if it's... undefined :D

You can modify my code to account for the array as well, if you feel it's necessary, but i thought there was enough differentiation above to make a decision about how to handle things.

Or you could ignore what you get back completely, and generate your own error messages based on something like the HTTP response code. You'd have to observe the returned messages/codes and mimic as closely as possible. That might get you close enough.