Skip to main content

Posts

Showing posts from January, 2025

Hierarchical Error - Reducing log messages and maintaining context

Something I see a lot, especially in node applications, is duplicate messages logged due to an exception being caught and logged in several places as the stack unwinds. For example with the following (contrived) code: const httpCall = () => {   const url = 'http://example.com';   try {     throw new Error('Something went wrong!');   } catch (error: any) {     log(error.message, { url });     throw error;   } }; The real error is here in httpCall , but some context about the error needs to be logged, so it is caught, logged and rethrown. const callService = () => {   const someContext = 'The service we called';   try {     httpCall();   } catch (error: any) {     log(`Service failed: ${error.message}`, { someContext });     throw error;   } } ; httpCall is called from a service wrapper, which has its own context which needs to be logged, so again the er...

Comments in Code: Just Don't Do It

How we use comments in code has come up a couple of times for me this week and when I looked, I realised we hadn't captured anything in the my teams's coding guide lines, so I added something:   Uncle Bob Says : "It is well known that I prefer code that has few comments. I code by the principle that good code does not require many comments. Indeed, I have often suggested that every comment represents a failure to make the code self explanatory. I have advised programmers to consider comments as a last resort." Comments should always be 'why', never 'what' and only when absolutely necessary. If you feel the need to write a 'what' comment, put the code in a well named (read descriptive) function instead.   There will be those of you who will be adamantly attached to your comments, but you don't need them. And at some point, in the past, now or in the future, you or someone else will update your code, making the comment wrong and forget to upd...