Skip to content

Instantly share code, notes, and snippets.

@tuannguyenssu
Created July 14, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuannguyenssu/5130ccc1006326f304b02227f6aec687 to your computer and use it in GitHub Desktop.
Save tuannguyenssu/5130ccc1006326f304b02227f6aec687 to your computer and use it in GitHub Desktop.
//--------------------------------------------------------------------------------------
// 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