DEV Community

loading...

Discussion on: Errors Are Not Exceptions

Collapse
ravavyr profile image
Ravavyr

Honestly, the worst thing I see is people using Try/Catch blocks to wrap a dozen potential issues and let it just blindly catch the failures regardless of how they interact with the rest of the system.

Most sites don't have one condition to check, they have half a dozen or more per feature, and ideally you check each one separately to validate the data and then TRY to process it and Catch any failures that result from that [eg. the "should never happen" conditions], while also handling the response data correctly to display any data errors to the users.

Personally I avoid using Try/Catch as much as I can and instead validate variables using conditionals and either manually logging errors or generating error messages to the user as needed. The manual logging is rare as again if you're catching errors like that, more often than not the only reason you'd log it is to see how someone is trying to abuse your code since you already know what the issue is and it's not really a problem that ever happens in a normal use-case. The best approach to someone trying to break into your system is to respond with a vague non-issue like "invalid token"...whether you use a token or not, the would-be hacker doesn't deserver a real response.

Exceptions can happen, but basic Errors should never be present in production code. If there are basic Errors in production it means you didn't test your work by actually running it/using it, I'm not talking about using the stupid linters that complain about semi-colons and 80 characters per line limits. I mean, really test your work to know it works correctly. You have [or have been given] requirements, if you don't, demand or write them, and meet them.