kask
kask
CC#
Created by kask on 7/13/2024 in #help
✅ Reducing exception usage, async methods
I've read a lot of using exceptions, best practices and such. As quick summary, the exceptions should be used on unexpected situations only (config errors, db connection errors..), not as validation errors and such. I understood, that for example, byte[] GetFileBytes(string filePath) shouldn't throw if file doesn't exist. I'm refactoring some my old projects as practice. For synchronous methods I've started using some TryGet pattern and it works great. But what about async methods? Async methods can't have out parameters. If we look at my earlier example and convert it into async method async Task<byte[]> GetFileBytes(string filePath), should I convert it to synchronous method or use some other pattern? Or should I throw a custom exception and attach original exception as inner? Catching all exceptions in multiple services and methods doesn't seem to be efficient ( catch (Exception e) when (e is PathTooLongException or DirectoryNotFoundException or IOException or UnauthorizedAccessException or FileNotFoundException or SecurityException) )
10 replies