This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//-------------------------------------------------------------------------------------- | |
// 4. Error Handling - Xử lý lỗi | |
//-------------------------------------------------------------------------------------- | |
//-------------------------------------------------------------------------------------- | |
// Không "throw ex" in khối catch | |
// Bad | |
try | |
{ | |
// Do something.. | |
} | |
catch (Exception ex) | |
{ | |
// Any action something like roll-back or logging etc. | |
throw ex; | |
} | |
// Good | |
try | |
{ | |
// Do something.. | |
} | |
catch (Exception ex) | |
{ | |
// Any action something like roll-back or logging etc. | |
throw; | |
} | |
//-------------------------------------------------------------------------------------- | |
// Tuyệt đối không nên bỏ qua các lỗi | |
// Bad | |
try | |
{ | |
FunctionThatMightThrow(); | |
} | |
catch (Exception ex) | |
{ | |
// silent exception | |
} | |
// Good | |
try | |
{ | |
FunctionThatMightThrow(); | |
} | |
catch (Exception error) | |
{ | |
NotifyUserOfError(error); | |
// Another option | |
ReportErrorToService(error); | |
} | |
//-------------------------------------------------------------------------------------- | |
// Sử dụng nhiều mức catch thay vì dùng điều kiện if | |
// Bad | |
try | |
{ | |
// Do something.. | |
} | |
catch (Exception ex) | |
{ | |
if (ex is TaskCanceledException) | |
{ | |
// Take action for TaskCanceledException | |
} | |
else if (ex is TaskSchedulerException) | |
{ | |
// Take action for TaskSchedulerException | |
} | |
} | |
// Good | |
try | |
{ | |
// Do something.. | |
} | |
catch (TaskCanceledException ex) | |
{ | |
// Take action for TaskCanceledException | |
} | |
catch (TaskSchedulerException ex) | |
{ | |
// Take action for TaskSchedulerException | |
} | |
//-------------------------------------------------------------------------------------- | |
// Keep exception stack trace when rethrowing exceptions | |
// Bad | |
try | |
{ | |
FunctionThatMightThrow(); | |
} | |
catch (Exception ex) | |
{ | |
logger.LogInfo(ex); | |
throw ex; | |
} | |
// Good | |
try | |
{ | |
FunctionThatMightThrow(); | |
} | |
catch (Exception error) | |
{ | |
logger.LogInfo(error); | |
throw; | |
} | |
try | |
{ | |
FunctionThatMightThrow(); | |
} | |
catch (Exception error) | |
{ | |
logger.LogInfo(error); | |
throw new CustomException(error); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment