Search code examples
design-patternserror-handlinglanguage-agnostic

When handling errors in code, is it acceptable to just return a single "error" value through the call chain back to the entry point?


I am running into a few instances in my code where valid user input is invalid for the operation being performed (Such as entering a schedule adherence entry for an employee that has no schedule because they were in training). This is an allowed action, but understandably creates an error down the road when calculating schedule adherence reports. In this example an error will be thrown when it finds no schedule for that employee at the time of the adherence entry.

In this case I would normally return an object that encapsulates some basic data on the entry and the schedule. If an error such as this occurs I return -1, and all proceeding methods just check for a -1, if it's found then they also return -1 instead of performing their usual actions. all the way back up to the start of the call chain where no more returns are expected and no final action is taken on a -1 value.

Is this an appropriate pattern to handle errors in your code? If not, what would be the preferable way to handle these?


Solution

  • It is one way to do it, but there are downsides:

    • you need each function along the way to handle the error
    • you lack any context when handling the error (you do not know why the error occured in the calling functions)

    A better approach is using the exception/try-catch mechanisms that most languages have. It allows you to handle the error in the function that you want (even at the top if you want), and adds context. It's also more scalable, robust and readable (everyone reading the code understand what an exception is).