Apex 26.1 Nice token limit error

Oracle APEX & PL/SQL Developer with 10 years of experience. Working mainly with manufacturing industry. My work is my passion. Avid gamer.
This one caught me with my guard down.
While testing NL2IR and the built-in Token Limit, I kept hitting this message:
"An unexpected error occurred." Not very helpful.
I looked at the AI response handler, tried a few things, and eventually gave up. I assumed there was some internal code that displays this whenever anything goes wrong during the LLM processing chain. Nothing can be done. Maybe a future release will add customization options.
Oh how wrong I was. This is APEX - everything is standardized. What we are seeing here is just an ORA error, specifically ORA-20962 with the APEX error code APEX.AI.ERROR. And ORA errors in APEX can be handled with the standard error handling function.
Reproducing the error
Set up a service that will fail immediately:
The important part is Maximum AI Token Limit - set it to 0.
Now go to Edit Application Definition → AI and assign this service.
Now all NL2IR and Assistant features in this app will fail with the "unexpected error" message. But it is not unexpected, and it is not really an error - it is a token limit check doing exactly what it should. So how do we give the user a proper message?
The fix
Create an error handling function:
create or replace function log_apex_error(
p_error in apex_error.t_error
) return apex_error.t_error_result
as
l_result apex_error.t_error_result;
begin
l_result := apex_error.init_error_result(p_error => p_error);
-- Handle AI token limit error with a user-friendly message
if p_error.ora_sqlcode = -20962
and p_error.apex_error_code = 'APEX.AI.ERROR'
then
l_result.message := 'You have exceeded your available AI tokens. Please contact your administrator.';
l_result.display_location := apex_error.c_inline_in_notification;
end if;
return l_result;
end log_apex_error;
/
The function hooks into the standard APEX error pipeline. It only modifies the message for that specific ORA code and passes everything else through unchanged.
Now add it to Edit Application Definition → Error Handling → Error Handling Function:
And that is it.
I actually figured this out during an APEX Office Hours session - someone else asked a related question and it clicked. If you are not joining those sessions, you should. Half the time the best insights come from other people's problems.
The same pattern works for any AI-related ORA error APEX might throw. If Oracle adds new error codes for other AI limit scenarios, you just add another condition to the same function.



