To get the SQL error code in embedded SQL is rather easy because you don't have to do anything for it. The variables SQLCOD, SQLCODE and SQLSTATE are automatically generated for you.
But if you want a descriptive message for the error code you have to do something, though even that is fairly easy.
dcl-s errorMessage char(1000); exec sql SELECT ... ; if (sqlcode < 0); exec sql GET DIAGNOSTICS CONDITION 1 :errorMessage = MESSAGE_TEXT; message_escape('Could not fetch data for xyz. SQLCODE: ' + %char(sqlcod) + ' - ' + %trimr(errorMessage)); endif;
Throwing an escape message after having an SQL error is rather natural because if you would have done native IO you also would have an escape message.
The procedure message_escape is part of the message service program hosted on Bitbucket.org.