29
Fri, Nov
0 New Articles

Practical RPG: APIs, Part 1 - Error Handling

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

The more I use APIs, the more I realize how powerful they are, but learning to use them is a process; this article provides a first step.

IBM offers programmers incredible access to the IBM i operating system, but no single avenue is more extensive and powerful than the Application Programming Interface (API) library. So many APIs exist that IBM requires an entire website just to provide access to the documentation. In this article, I'll show you how I've been using this vast resource to advance my application programs.

We'll Begin at the End

Before we start working with specific APIs, I want to cover what might be the most powerful piece of the puzzle: the API error-handling process. For a large percentage of the APIs, IBM provides a very consistent yet flexible way to handle error conditions that supports three techniques, depending on your programming needs. Those three techniques roughly mirror the way we handle errors in CL programming:

  • Just let the error happen (and halt the program).
  • Monitor the error and ignore it.
  • Handle the error with condition-specific programming.

Let's take a look at all of three of these in a specific circumstance. A very common task is to check to see whether an object exists. This is one of those system functions that can be executed either by a CL command or via an API, so it works very well to illustrate the point. Let's start with the appropriate CL code:

CHKOBJ     OBJ(MYLIB/MYFILE) OBJTYPE(*FILE)

With this command, if the file MYFILE does not exist in library MYLIB, an error will occur. What happens next depends on what else you do in your program. If you provide no other programming, the program will halt, sending message CPF9801with the text "Object MYFILE in library MYLIB not found" to the user (or to the system operator in the case of batch jobs). The user can respond to the error message, and the program can continue (or not, depending on the response).

However, you can also do a couple of things to mitigate that hard halt. One is to just follow the CHKOBJ command with the following line of code:

MONMSG     MSGID(CPF0000)

By putting this statement immediately after the CHKOBJ, you will ignore the CPF9801 message. Because I specified CPF0000 (with the four zeros), we'll also ignore any other message starting with CPF. However, ignoring errors is often not a good idea, so let's see the third case:

CHKOBJ     OBJ(MYLIB/MYFILE) OBJTYPE(*FILE)

MONMSG     MSGID(CPF9801) EXEC(DO)        

   CRTPF     FILE(MYLIB/MYFILE) RCDLEN(80)

ENDDO                                      

In this case, we check for a specific error, and if it occurs, then we do something in response; in this case, if the file is not found, we create it. Because we coded the specific message ID (CPF9801) in the MSGID keyword, any other errors will actually halt just as if we hadn't coded a MONMSG at all. You can instead follow this with more MONMSG instructions to handle other errors and then finally with generic handlers such as MONMSG MSGID(CPF0000) to handle unexpected errors. Hopefully, this is just review; it's just meant to get us to the API programming. If you're unfamiliar with this subject matter, you can learn more about CL programming through books such as Ted Holt's masterpiece, Complete CL, available from our own wonderful MC Press.

Handling Errors in APIs

As I've said already, the majority of IBM i APIs use the standard API error technique. Notable exceptions include the UNIX-type APIs such as system and iconv, which use the errno value to indicate the error. I'll discuss that in a different article that will focus on the UNIX-type APIs. Today, though, we will review the standard API error structure. Let's take a look at just the API error structure itself. It has three variations:

      dcl-ds ApiThrow;

      *n int(10) inz(0);

      *n int(10) inz(0);

     end-ds;

     dcl-ds ApiIgnore qualified;

      BytPrv int(10) inz(8);

      BytAvl int(10) inz(0);

     end-ds;

     dcl-ds ApiError qualified;

      BytPrv   int(10) inz(%size(ApiError));

      BytAvl   int(10) inz(0);

      MsgID   char(7);

      reserved char(1);

      MsgDta   char(80);

     end-ds;

The third iteration (ApiError) is the most flexible; it is set up to return the error message data. If your command fails, the error message ID and message data will be returned in the MsgID and MsgDta fields, respectively, in the ApiError data structure. We'll look at that one in a moment. But first let's discuss ApiIgnore and ApiThrow. These are the shortcut structures; each is only eight bytes long. The first four bytes tells the API how much error information you want returned, while the second are used by the API to communicate whether an error occurred. If you pass zero in the first bytes (as is done in ApiThrow), then any error causes a halt. If, on the other hand, you pass a value of exactly 8 (eight), then an error will not cause a halt, but a non-zero value will be returned in the second four bytes. Please note that the subfields BytPrv (bytes provided) and BytAvl (bytes available) exist in both ApiError and ApiIgnore, which is why I use the qualified modifier. I'll leave it as a reader exercise to determine why I didn't specify qualified for ApiThrow.

Returning to ApiError, you'll see that it uses a different technique for the first value. The BytPrv field is initialized to the size of the overall ApiError data structure. This would change based on, for example, the length of the MsgDta field. And that's exactly what we use it for: to return a larger (or smaller) amount of message data. We'll see how all this works in the next section.

Calling an API

It's time to call an API. Two APIs exist that provide similar functionality to CHKOBJ. One is QSYCUSRA, which checks the authority, but for those cases when all you're doing is checking the existence of the object, QUSROBJD is a better fit. It simply retrieves the object description, but it returns an error if the object is not found. The prototype for the call is pretty standard: there's a data structure that defines the data returned, and a call. Here's the free-format definition:

      dcl-ds OBJD0100 qualified;

      BytRet   int(10);

      BytAvl   int(10);

      ObjNam   char(10);

      ObjLib   char(10);

      ObjTyp   char(10);

      RtnLib   char(10);

      ASP     int(10);

      ObjOwn   char(10);

      ObjDom   char(2);

      ObjCrt   char(13);

      ObjChg   char(13);

     end-ds;

     dcl-pr QUSROBJD extpgm;

      iData   like(OBJD0100);

      iDataLen int(10) const;

      iFormat char(10) const;

      iObjlib char(20) const;

      iType   char(10) const;

      iError   char(1) options(*varsize);

     end-pr;

You see the OBJD0100 data structure, which contains the data that we'll be returning. Like many other APIs, the QUSROBJD API can return data in multiple formats. The format used is determined by one of the parameters passed into the API. In this case, the iFormat parameter identifies which format to use. Other formats return more data; you can see more about them and the QUSROBJD API in general on the IBM website. Today we're just going to focus on the last parameter in the prototype, iError.

Since we may pass parameters of different lengths to this API depending on the kind of error-handling we need, the correct prototype definition is to use options(*varsize) as part of the subfield definition. This causes the compiler to ignore the length check and basically allows you to pass any size of parameter. This means that you and the API have to somehow agree on the length of the parameter. In the case of the ApiError structure, it's done in those first four bytes that are initialized with %size(ApiError). So let's write the actual program that uses all of this:

      dcl-pi *n;

      iLib char(10);

      iObj char(10);

      iTyp char(10);

     end-pi;

     QUSROBJD(

      OBJD0100: %size(OBJD0100): 'OBJD0100': iObj+iLib: iTyp: ApiError);

     QUSROBJD(

      OBJD0100: %size(OBJD0100): 'OBJD0100': iObj+iLib: iTyp: ApiIgnore);

     QUSROBJD(

      OBJD0100: %size(OBJD0100): 'OBJD0100': iObj+iLib: iTyp: ApiThrow);

     *inlr = *on;

      return;

As you can see, after setting up the prototypes and structure, the code is actually very straightforward. You can refer to the website for a more in-depth explanation of the parameters that I need to pass in, but I can describe them briefly here. The first three identify the receiver variable: the variable itself, the size of the variable, and the format, OBJD0100. The next two are the input parameters for the actual object. The first is the standard IBM construct for a qualified object, which is the 10-character object name and the 10-character library name concatenated into one 20-character field. Next is the object type. Finally, we include the (optional) error-handling structure. I have three different calls using the same values, just with different error handling.

You can now copy all the code above into an RPGLE member and compile it and call the program to see how each works. The first uses ApiError, which returns the message ID and data. In fact, if I call the program with an object that doesn't exist, I can see the following data in ApiError when using the debugger:

EVAL apierror                      

APIERROR.BYTPRV = 96              

APIERROR.BYTAVL = 36              

APIERROR.MSGID = 'CPF9811'        

APIERROR.RESERVED = '0'            

APIERROR.MSGDTA =                  

         ....5...10...15...20...25.

     1   'NOOBJECT QGPL          

Each subsequent call acts differently. The second call returns nothing except the value 36 in the second parameter. This is the indication that an error occurred. And finally, the third call causes the error to be thrown back to the program, and I get a hard halt saying the call failed (as well as seeing the CPF9811 error in the joblog).

More to Come

Today's article is just an introduction to the universe of API programming. You can find a wealth of great information online, including the fantastic IBM System i APIs at Work book, also available here at MC Press. In upcoming articles, I'll be introducing you to other APIs, along with techniques I happily incorporated from the work of others, including Carsten Flensberg's incredible website, APIs My My My.

 

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 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. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • 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 company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY 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. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) 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:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. 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:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot 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:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

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

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

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

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

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? 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: