SqlException catch e manipulação
Q: Existe uma maneira melhor de lidar com SqlException
Os exemplos abaixo se baseiam na interpretação do texto na mensage
Eg1: Eu tenho uma tentativa existente de captura, se uma tabela não existi
Ignore o fato de que eu poderia verificar se a tabela existe em primeiro luga
try
{
//code
}
catch(SqlException sqlEx)
{
if (sqlEx.Message.StartsWith("Invalid object name"))
{
//code
}
else
throw;
}
Eg2: sem a captura try mostrando a exceção de chave duplicada
if (sqlEx.Message.StartsWith("Cannot insert duplicate key row in object"))
Solution: O início do meu SqlExceptionHelper
//-- to see list of error messages: select * from sys.messages where language_id = 1033 order by message_id
public static class SqlExceptionHelper
{
//-- rule: Add error messages in numeric order and prefix the number above the method
//-- 208: Invalid object name '%.*ls'.
public static bool IsInvalidObjectName(SqlException sex)
{ return (sex.Number == 208); }
//-- 2601: Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.
public static bool IsDuplicateKey(SqlException sex)
{ return (sex.Number == 2601); }
}