The API Corner: What to Do with Messages in the Application Program

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Let's explore detecting and handling API application-related error messages.


The past several articles in this column have been related to detecting and managing messages that have been sent to other jobs on the system. We looked at handling message watches, validating inquiry message responses, and providing responses to inquiry messages. Today, we will continue looking at messages but turn inward. This article will review some of the approaches available to handle message conditions that exist within the current application program.


Most system APIs, at least those that start with a Q, provide you with an error code parameter that allows you to control how errors detected by the API should be returned to your program. There are two formats to the error code parameter, with the most important element being the Bytes provided field, which exists in both formats. When Bytes provided is set to zero, you are instructing the API to return any error information back to your program as an escape message. When Bytes provided is eight or greater for format ERRC0100, and twelve or greater for format ERRC0200, you are instructing the API to return any information back to your program in the error code parameter itself.


In writing an application program, there some situations where I anticipate specific errors in calling an API. To avoid the overhead of the system sending and the application program then receiving messages, I prefer to receive error-related information directly through the error code parameter. In other cases, I do not expect any error in calling an API and prefer using escape messages. For these reasons, I generally start out my programs with the following:


d/copy qsysinc/qrpglesrc,qusec                         


dErrCde           ds                  qualified        

d Common                              likeds(QUSEC)    

d ErrMsgTxt                    512                   



  QUSBPRV = 0;                             

  ErrCde.Common.QUSBPRV = %size(ErrCde);






The /copy directive copies in the error code parameter definition as provided by IBM in the QSYSINC library. This library can be installed by restoring option 13 of the i operating system. IBM defines the ERRC0100 error code format using the data structure name QUSEC, and the subfield QUSBPRV represents the Bytes provided field of ERRC0100. I use this definition as-is when I want escape messages sent in response to API-related errors. The statement QUSBPRV = 0; sets the Bytes provided field of the QUSEC data structure to zero, indicating that error conditions should be returned as exception messages.


I also define a version of the error code structure named ErrCde. ErrCde is defined with the same first 16 bytes as the QUSEC data structure but has an additional 512 bytes allocated for possible message replacement data that may be returned in the ErrCde error code structure when an API returns error-related information. The use of 512 bytes for ErrMsgTxt is somewhat arbitrary and dependent on the error message replacement text that you anticipate coming back from a given API call. I find 512 bytes sufficient for most system messages as long as I am not expecting long IFS path names to be returned. The statement ErrCde.Common.QUSBRV = %size(ErrCde); sets the Bytes provided field of the ErrCde data structure to 528, indicating that error conditions should be returned in the ErrCde data structure rather than as exception messages.


The "monitor" and associated on-error, endmon operation codes are, among other things, an admission that, while I strive to write "perfect" code, I occasionally fall short of that goal. I use a global monitor to ensure that my program has an opportunity to send an appropriate error message for the application rather than a potentially cryptic error message from either RPG run-time (for instance RNQ0121 – An array index is out of range) or the i operating system (MCH0603 – Range of subscript value of character string error), neither of which tells the poor user to call support. Rather than using a monitor, I could use RPG-provided alternatives, such as a program exception/error subroutine (*PSSR) and a program status data structure (PSDS), but, as you will see later, I prefer a more granular approach to error handling than catchall PSSRs per procedure. The ability to nest monitor groups and have specific on-error processing directly associated with the failing code sold me on monitor groups long ago.


Returning to the discussion of error code usage, let's say we need to determine if a given object exists and, if not, have the application create the object. One approach to finding out if the object exists would be to use an API such as Retrieve Object Description (QUSROBJD). The QUSROBJD API will retrieve object information about a specific object and, while we don't really care about this object information, if anything is returned, then we know that the object exists. As we are checking for the existence of an object, this is a scenario where it is quite reasonable for the API to return an error condition such as CPF9801 – Object &2 in library &3 not found.


In this situation, I would use the ErrCde error code parameter as shown below:


 /copy qsysinc/qrpglesrc,qusrobjd                                    

 /copy qsysinc/qrpglesrc,qusec                                        


dRObjD            pr                  extpgm('QUSROBJD')             

d Receiver                       1    options(*varsize)              

d LenReceiver                   10i 0 const                          

d Format                         8    const                          

d ObjName                       20    const                          

d ObjType                       10    const                           

d ErrCde                              likeds(QUSEC) options(*nopass) 

d ASP                            1    const options(*varsize :*nopass)


dErrCde           ds                  qualified                      

d Common                              likeds(QUSEC)                  

d ErrMsgTxt                    512                                   


dQualName         ds                                                  

d Name                          10    inz('SOMEOBJECT')               

d Library                       10    inz('SOMELIB')                  


dType             s             10    inz('*USRSPC')                  





  QUSBPRV = 0;                                                        

  ErrCde.Common.QUSBPRV = %size(ErrCde);                               


  RObjD(QUSD0100 :%size(QUSD0100) :'OBJD0100' :QualName :Type :ErrCde);

  if ErrCde.Common.QUSBAVL > 0;                                       


        when ErrCde.Common.QUSEI = 'CPF9801';                         

             // Create the user space                                 

        when ErrCde.Common.QUSEI = '???????';                        

             // Additional error checks that I will handle          


             // Something more than I expected so send 

             // appropriate message(s) and end         




  // Continue processing and eventually end the program normally    


  *inlr = *on;                                                      




  // ...                                                            





A few points concerning the program code provided above: First and foremost, whenever you use an error code with a Bytes provided field set to a non-zero value, the first thing you need to do is examine the associated Bytes available field (ErrCde.Common.QUSBAVL in the example). If the value is greater than zero, then an error was encountered by the API and you must take appropriate action. You will not be sent an escape message from the API. To continue the application program without awareness that an error has occurred is just asking for trouble. QUSBAVL incidentally is the name of the field, within the QUSEC error code structure provided by IBM, that contains the Bytes available.


When Bytes available is greater than zero, I recommend entering a "select" group so that you can easily diagnose, and perhaps correct, the problem (and ensure with the "other" operation code that all possible error conditions are addressed in one way or another). In order to do a good job in the select processing, you will need to examine those errors that might be returned by the API. This list of possible error conditions (messages) can be found at the end of the API documentation in the Information Center.


In the case of QUSROBJD, one message condition of note is CPF9801 – Object &2 in library &3 not found. In the case of the sample program, the one shown "when" test is for CPF9801 with the recovery action being that the object is created. QUSEI incidentally is the name of the field, within the QUSEC error code data structure provided by IBM, that contains the Exception ID.


Examining the various error conditions that can be returned by the API may give you food for thought. You will notice for instance that the following error can be returned: CPF9810 – Library &1 not found. What do you want to do if the library SOMELIB doesn't exist? If it would be appropriate for the application to create the library, then a specific "when ErrCde.Common.QUSEI = CPF9810" and a recovery action of first creating the library followed by then creating the object may be called for.


Otherwise a more generic "when" such as shown below may be sufficient.


        when ((ErrCde.Common.QUSEI = 'CPF9810') or             

              (ErrCde.Common.QUSEI = 'CPF9802') or             

              (ErrCde.Common.QUSEI = 'CPF9820'));              

             // Send the original error information followed    

             // by a message indicating an environmental       

             // problem external to the application            


This "when" operation is checking for three possible error conditions that may be outside of the application program's control and may need to be addressed by the system administrator. The error conditions are CPF9810 – Library not found, CPF9802 – Not authorized to object, and CPF9820 – Not authorized to the library. In this case, sending the original error message (to document the specifics of what went wrong) followed by an application error message telling the user to contact the system administrator for resolution may be more appropriate. In a future article, we will look at the specifics of how to actually send these messages.


Note that I am greatly simplifying the work that should be done when examining and handling various error conditions. In the case of CPF9810, for instance, there are many possible recovery messages that may be sent. If our application is a command processing program (CPP), then the CPF9810 may indicate a user error when specifying the library name, in which case the end user should resolve the problem. If our application is intended to be called by other programs, and not directly as a CPP, then the CPF9810 may indicate a product configuration problem for the system administrator to resolve. If our application really has the library name hardcoded as in the example, then the CPF9810 may indicate an internal failure within the product, and software support is need to resolve the problem. These types of decisions can only be made by you within the context of the current application program.



Other error conditions that can be returned by the API will indicate that "something" is really wrong and that the application program has an internal problem (or in some cases that the job itself is experiencing internal problems). These error conditions, such as CPF3C21 – Format name not valid, should never occur once you have debugged the application and put it into production. But if they do occur, then sending the original error message followed up by an application error message telling the user to contact the system administrator, and for the administrator to then contact you for resolution, would be more appropriate. Unlike the case of CPF9810, the administrator can do little in resolving a CPF3C21. These are the types of error conditions that would be addressed by the "other" operation code of the "select" group. Again, how to actually send these messages will be shown in a subsequent article.


Now let's look at the case where we have no reasonable expectation that the API will return an error condition. Let's say the application program needs to determine the date format in use by the current job. One way to access this information is to use an API such as Retrieve Job Information (QUSRJOBI). The QUSRJOBI API retrieves specific information about a job, and, while many things could go predictably wrong when accessing job information related to any arbitrary job (for instance, the job is no longer on the system), we would not expect any difficulty in accessing job-related information for the current job. Or at least we would not expect any errors once we have debugged the application to ensure that correct format names are in use, receiver variable sizes are correct, etc.—in other words, the types of error conditions found at the end of the QUSRJOBI API documentation.


In this situation, I would use the QUSEC error code parameter as shown below:


/copy qsysinc/qrpglesrc,qusrjobi                                  

 /copy qsysinc/qrpglesrc,qusec                                    


dRJobI            pr                  extpgm('QSYS/QUSRJOBI')     

d Receiver                   65535    options(*varsize)           

d LenReceiver                   10i 0 const                       

d Format                         8    const                       

d QualJobName                   26    const                       

d IntJobID                      16    const                       

d ErrCde                         1    options(*varsize :*nopass)  

d ResetPfr                       1    options(*nopass)            


dErrCde           ds                  qualified                   

d Common                              likeds(QUSEC)               

d ErrMsgTxt                    512                                





  QUSBPRV = 0;                                                      

  ErrCde.Common.QUSBPRV = %size(ErrCde);                           


  RJobI(QUSI0400 :%size(QUSI0400) :'JOBI0400' :'*' :' ' :QUSEC);   


  // Continue processing and eventually end the program normally   


  *inlr = *on;                                                      




     // Something more than I expected so send                     

     // appropriate message(s) and end                             





As the Bytes provided field for the QUSEC error code structure is set to zero, the QUSRJOBI API will send an escape message if an error is encountered. The escape message will trigger the monitor, and control will be passed to the on-error block of the program. Here, you find a comment similar to what is found in the "other" operation of the previous ErrCde example. Unlike the ErrCde "other" logic, the application here does not need to send the original error message. The original error message was sent by the system and so is currently in the job log for review by the operator. We simply need to send the message for the user of the program to contact the administrator and for the administrator to, in turn, contact you. It is worth pointing out that this same on-error block is what will also run if we encounter an RPG run-time error such as an invalid array index. This one block of code represents a central location in the application for the management of totally unexpected error conditions.


One note of caution: if you decide to change the above code and introduce an error in the call to QUSRJOBI, please note that the on-error block is not currently doing anything; it's just a comment. Introducing an error, for instance by specifying an invalid format name for the third parameter, will quickly remind you that the RPG cycle is still alive and well!


So now we've reviewed how to detect API application-related errors. The next article will discuss how to report these error conditions back to the user, the system administrator, and you.


In the meantime, if you have any API questions, send them to me at This email address is being protected from spambots. You need JavaScript enabled to view it.. I'll see what I can do about answering your burning questions in future columns.


Bruce Vining

Bruce Vining is president and co-founder of Bruce Vining Services, LLC, a firm providing contract programming and consulting services to the System i community. He began his career in 1979 as an IBM Systems Engineer in St. Louis, Missouri, and then transferred to Rochester, Minnesota, in 1985, where he continues to reside. From 1992 until leaving IBM in 2007, Bruce was a member of the System Design Control Group responsible for OS/400 and i5/OS areas such as System APIs, Globalization, and Software Serviceability. He is also the designer of Control Language for Files (CLF).A frequent speaker and writer, Bruce can be reached at 

MC Press books written by Bruce Vining available now on the MC Press Bookstore.

IBM System i APIs at Work IBM System i APIs at Work
Leverage the power of APIs with this definitive resource.
List Price $89.95

Now On Sale



Support MC Press Online





  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things

    Read Node.js for Enterprise IBM i Modernization Now!


  • Profound Logic Solution Guide

    SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation.
    Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects.
    The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the companyare not aligned with the current IT environment.

    Get your copy of this important guide today!


  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.


  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline



  • The Power of Coding in a Low-Code Solution

    LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed.
    Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Why Migrate When You Can Modernize?

    LANSABusiness users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.


  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact


  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using as a pre-built development environment



  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.



  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.



  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails


  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.



  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed.
    Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY the one package that solves all your document design and printing challenges on all your platforms.

    Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. How can you be sure you won’t miss important system events?
    Automate your message center with the Robot Message Management Solution. Key features include:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing.
    Manage your reports with the Robot Report Management Solution. Key features include:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.