Search code examples
delphierror-handlingdelphi-xe2dbexpress

Handling DbExpress Sql Error Code 245


I am trying to build a scheduler application for my semestre exam, and I am interogating the database if a teacher has classes in a certain week, certain day and a certain hour. Is there a way to treat Sql Error Codes in Delphi Xe2 using DBExpress? I have a query performing my interogation(I let the users to select the parameters) on SQL Server2008, and here is the issue; If an user lets one parameter field empty, my application shows the message in the image; well this is not a user friendly way of showing error messages, so I tried to handle the exception without any succes: this is my code that i wrote to query SQL Server:

with DataModule1.QueryV1 do
 Try
    Close;
    SQL.Clear; // clear command sql if there is
    SQL.Add ('SELECT * FROM OrarC WHERE IDZi =' +
    QuotedStr(LlbZiua.KeyValue)+ 'and IDInterval=' + QuotedStr(LlbIntOrar.KeyValue) +
     'and IDSala='+ QuotedStr(EdtIDSala.Text)+ EdtSaptamana.Text);
    Open;
  except
    on E:TDBXError do begin
      showmessage('Error!');
    end;
  End;

on E:TDBXError I have also tried E:EDataBaseError and the result is the same; It would be good to handle the error by the SqlErrorCode returned but I don`t know how to get that. enter image description here


Solution

  • Run your program under the debugger and observe the actual class of the exception that's raised, or you can get the exception class at runtime with something like:

      ..
    except on E: Exception do
      ShowMessage(E.ClassName);
    end;
    

    If it is indeed a TDBXError then you could use for example

    uses
      dbxcommon;
    
    except
      on E: TDBxError do begin
        if (E.ErrorCode = TDBXErrorCodes.InvalidArgument) then
          ..
    

    But as far as I can see 245 is not one of TDBXErrorCodes, so possibly you've got an other exception. If it's an EDatabaseError there's nothing much to do, since the class does not have an error code field.

    Not quite relevant but also see Data.DBXCommon.TDBXConnection.OnErrorEvent to be able to manage dbexpress exceptions at a central location.