when I connect to database and execute a query, then if there occurs any exception then I want to fetch only the reason of exception not the full message , so that in my log I can log only the reason of exception for example. one exception is below by applying getMessage() o开发者_开发百科n exception object in catch block
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'tty'.So I want to fetch only "Invalid object name 'tty'".
The exception will occur only due to executeUpdate() method. so exception may be anything related to database or sqlquery not just Invalid object name 'tty'.
I can't see anything obvious in SQLException
, but I can think of two options:
- Remove everything in square brackets, possibly with a regex.
- If you're always using the same driver, just remove the leading predictable leading substring
Sample code for the second option:
private static final String MESSAGE_PREFIX =
"[Microsoft][ODBC SQL Server Driver][SQL Server]";
...
String message = exception.getMessage();
if (message.startsWith(MESSAGE_PREFIX))
{
message = message.substring(MESSAGE_PREFIX.length());
}
That's likely to be considerably easier than the first option, but is obviously rather more brittle in the face of driver changes. I wouldn't be surprised to see the message format change for different drivers anyway though...
as @Jon Skeet suggested I think better to use first option for regex and apply following code in catch block
Pattern p=Pattern.compile("\[.*\]");
Matcher m=p.matcher(e.getMessage());
int end=0;
while(m.find()){
end=m.end();
System.out.println(m.start()+" "+m.end());
}
System.out.println(e.getMessage());
System.out.println(e.getMessage().substring(end));
then it gives following output
0 47
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'tty'.
Invalid object name 'tty'.
精彩评论