Say I have an application that uses thread to download files through HTTP or FTP. I can imagine a few things going wrong in the background that would require some error handling:
- The distant host becomes unavailable.
- The download speed is too slow.
- Some data is corrupt (if checks in place).
- No data is being sent.
- Content doesn’t correspond with expected file type.
- Reported size and data don’t correspond.
- …
How could these be handled in such a way as to relay an error back to the main application ? Or abort if unrecoverable ?
This is a pretty general question with a number of possible solutions. It depends highly on what information the thread is currently reporting back to the main application. If, for example, it is returning some remote file-contents in a
Stringthennullcould indicate some sort of problem with the data. If you want more specific information then you will need to maybe create some sort ofJobStatusclass that encapsulates some of the error conditions you mention. Maybe the class also includes the remote file contents or the actual work payload.In terms of passing back the information. The
Runnableclass could have some sort ofgetStatus()method if you are not using aCallable<...>andExecutorServicethread-pools. You could also pass aWorkRequestclass into yourThreadthat it fills out for the job at hand which could include information about any errors encountered.Typically I tend to rely on logging to show the actual source and details of the problem and rely on exceptions thrown by
Future.get()to relay back that my processing thread had some sort of problem. But again, it is hard to determine what makes sense in your environment without a lot more context.