Search code examples
javajdbcexceptionsqlexceptionjdbc-odbc

how to fetch only reason from java exception


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() on 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'.


Solution

  • 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...