Tag Archives: application

Best Practices for API Error Handling


As a web developer, we all don’t want to see Error codes in an API response, neither do you. When it happens to you, it can mean one of two things — there was something wrong in your request or your handling that the API simply couldn’t parse the passed data, or the API itself has so many problems. In either situation, traffic comes to a sudden end, and we start trying to discover the cause and solution for that.

Although being unpleasant, errors, whether in code form or simple error response, are incredibly useful. Error codes are probably the most useful diagnostic element in the API space.

Today, we’re going to discuss about the importance and the usefulness of error responses and handling approaches. There are some common error code classifications the average user will encounter, as well as some examples of these codes in action that you need to know.

The Value of Error Codes
As explained above, error codes are surprisingly, but incredibly useful. Error codes in the response stage of an API are essential in communicating failure from a developer to a user. This stage is a direct communication between client and API. It’s considered as the most important step towards informing the user of a failure, as well as boosting the error resolution process.

An error comes randomly and sometimes it’s beyond our knowledge. That’s why error responses are the only constant, consistent communication that we, as the user, can rely on when an error has occurred. Error codes can both clarify the situation, as well as communicate the intended functionality.

For example, an error code such as “401 Unauthorized – Please Pass Token.” You understand the point of failure in that response, especially that the user is unauthorized. However, you also figure out the intended functionality, which means that the API requires a token, and that token must be passed as part of the request in order to obtain authorization.

With a simple error code and resolution explanation, you have already identified the cause of the error, as well as the intended functionality and method to fix that error. It is very useful, especially for the amount of data that is actually returned.

HTTP Status Codes
Before we deeply discuss about error codes and what makes a code good, we need to sort out the HTTP Status Codes format. These codes are the most frequent status codes that the average user will encounter, not only in terms of APIs but also in terms of general internet usage. Although there are other protocols and have their own system of codes, the HTTP Status Codes dominate API communication, and vendor-specific codes tend to be derived from these ranges.

  • 1XX – Informational

The 1XX range has two basic functionalities. First, in the transfer of information concerning the protocol state of the connected devices — for example, 101 Switching Protocols is a status code noting that the client has requested a protocol change from the server, and that the request has been approved. The 1XX range also elucidates the state of the initial request. For example, 100 Continue, notes that a server has received request headers from a client, and that the server is waiting for the request body.

  • 2XX – Success

The 2XX range notes a range of successes in communication, and combines several responses into specific codes. The first three status codes excellently determine this range, like 200 OK means that a GET or POST request was successful, 201 Created indicates that a request has been brought to completion and a new resource has been created for the client, and 202 Accepted shows that the request has been accepted, and that processing has begun.

  • 3XX – Redirection

The 3XX range is all about the status of the resource or endpoint. When this kind of status code is sent, it confirms that the server is still accepting communication, but that the contacted point is not the accurate point of entry into the system. 301 Moved Permanently denotes that the client request did reach the correct system, but this request and all future requests should be managed by a different URI. This is very convenient both in subdomains and in moving a resource from one server to another.

  • 4XX – Client Error

The 4XX series of error codes is probably the most well-known because of the famous 404 Not Found status, which is a prominent marker for URLs and URIs that are formed in the wrong way. However, other more useful status codes for APIs are in this range.

414 URI Too Long is a common status code, indicating that the data pushed through in a GET request is too long, and should be changed into a POST request. Another common code is 429 Too many Requests, which is used for rate limiting to note a client is attempting too many requests simultaneously that their traffic is being rejected.

  • 5XX – Server Error

The 5XX range is reserved for error codes notably related to the server functionality. Whereas the 4XX range is the client’s responsibility (meaning that it is a client failure), the 5XX range explicitly notes failures with the server. Error codes such as 502 Bad Gateway, which marks the upstream server, has failed and that the current server is a gateway, further reveal server functionality as a method of showing where failure is transpiring.

Making a Good Error Code
With a strongly-built comprehension of HTTP Status Codes, we can start analyzing what actually makes for a good error code, and what makes for a bad error code. Quality error codes not only convey what went wrong, but also why it went wrong.

Excessively obscure error codes are very inconvenient. Imagine that you are trying to make a GET request to an API that manages digital music inventory. You’ve submitted your request to an API that usually accepts your traffic, you’ve passed the correct authorization and authentication credentials, and you think the server is ready to respond.

You send your data, and receive this kind of error code: 400 Bad Request. Without additional data and without more information, what does this mean? It’s in the 4XX range, so you know the problem was on the client side, but it doesn’t explain and solve anything, other than “bad request.”

This explains that a “helpful” error code is not as helpful as it should be. We could easily make that same response helpful and clear with less effort. Good error codes must pass three essential criteria in order to be functional, such as:

  • An HTTP Status Code, so that the source and realm of the problem can be confirmed with ease;
  • An Internal Reference IDfor documentation-specific notation of errors. In some cases, this can substitute the HTTP Status Code, as long as the internal reference sheet inserts the HTTP Status Code scheme or similar reference material.
  • Human readable messagesthat conclude the context, cause, and solution for the existing error.

From this discussion, we can conclude that error codes are useful if inserted with messages conveying what goes wrong and why it goes wrong, topped off with the human readable messages emphasizing the solution that we can take and do to handle it. That way, we can effortlessly handle it when future errors occur spontaneously.

Knowing What Is Augmented Reality and Its Implementations


Augmented reality is a new digital phenomenon that changes the environment around you into a digital interface. It places virtual objects in the real world and in real-time. Therefore, it provides the power of learning and technology together.

Nowadays, you can experience augmented reality through a wide variety of activities. This is because AR aims to simplify human’s lives by combining virtual information to surroundings view of real environment. The usage of AR is limited for Mobile. Although, it also works on some desktop browsers but it doesn’t produce the same experience as a smartphone did. That is why this area is mostly developed by mobile apps developers.

In general, there are 3 main categories of augmented reality (AR) that you can distinguish:

Augmented Reality 3D viewers
This type of AR allows users to locate life-size 3D models in your environment with or without the use of trackers. Trackers are better known as simple images that 3D models can be applied to in Augmented Reality.

Augmented Reality Browsers
This AR’s type will enhance your camera display with contextual information. Hence, you can display any history or estimated value of one building only by pointing your smartphone at it.

Augmented Reality for Gaming
The last and maybe the most popular way to experience Augmented Reality is through gaming. Have you ever heard or played Pokémon? This game utilizes your actual surroundings and has become very popular because of it.

All of these 3 categories have been applied to many fields of lives. Hence, in this article, we would like to broaden your knowledge about the implementation of AR. Below are some of the good examples of AR that you can learn for:

Augmented Car Finder
If you often forget where you park your car, augmented car finder can be a good idea for you. Augmented Car Finder will help you identify location of your vehicle in a maze of parking lots. The apps will show a marker where your car is parked; it also shows the distance between you and your car’s location. Moreover, it will guide you to reach your car area.

With Layar, you can connect digital content with the real world. There are many more advantages that you can get through Layar. For instance, magazines come alive with videos right on the page, easily buy items with direct mobile shopping links, connect with links to web content and share items on social  media, and browse and view thousands of Geo Layers to find stuff nearby, like ATMs, restaurants, historical locations.

EyeDecide AR app
AR implementations are also developed in healthcare industry. One of them is EyeDecide AR app. EyeDecide AR app is created to provide patient-engagement tools for healthcare providers. Developers can use the camera to simulate the vision of a patient. Here are some basic features of this app:

  1. Leverage interactive anatomical models to enhance patient understanding.
  2. Effectively educate patients by comparing normal and abnormal images and using 3D animation videos of most common conditions.
  3. Improve patient and surgical retention by helping patients make more informed decision about the care.


The Activity Lifecycle of Android


In Android activity lifecycle, there are four activities that permit the activity to know a state has changed. They include creating, stopping or resuming an activity or destroying the process in which the activity resides.

Through activity lifecycle concept, web developers and android developers can learn to understand how your activity works properly when the user leaves and re-enters the activity. This means each callback permits you to perform specific work that’s appropriate to a given change of state. Doing the right work at the right time and handling transitions properly make your app more robust and performant. By having good implementation of the lifecycle callbacks will ensure your app keeps away from several things bellows:

  • Consuming valuable system resources when the user is not actively using it.
  • Crashing or losing the user’s progress when the screen rotates between landscape and portrait orientation.
  • Losing the user’s progress if they leave your app and return to it at a later time.
  • Crashing if the user receives a phone call or switches to another app while using your app.

In the next section, we will discuss the lifecycle paradigm and then we will explain each of the callbacks.

Activity-Lifecycle Concepts

The Activity class offers a core set of six callbacks to navigate transitions between stages of the activity lifecycle, such as: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). The system navigates each of these callbacks as an activity enters a new state.

Figure 1 presents a visual representation of this paradigm.



The chart above shows the activity states, the activity will be more complex depends on your requests. If you only implement a simple activity state, you don’t need to implement all the lifecycle methods. But, you still need to understand all of the lifecycle and implement those that ensure your app runs the way users want.

Lifecycle Callbacks

This section provides conceptual and implementation information about the callback methods used during the activity lifecycle.


This callback is the first stage when the system first creates the activity. The activity enters the created state. You perform basic application startup logic that happens only once for the entire life of the activity, in the onCreate()method. For example, your implementation of onCreate()might bind the data to lists, initialize background threads, and instantiate some class-scope variables. This method receives the parameter savedInstanceState, which is a Bundle object containing the activity’s previously saved state. The value of the object is null, if the activity has never existed before.

To understand fundamental setup for the activity, such as declaring the user interface, defining member variables, and configuring some of the UI. In this example, by passing file’s resource ID R.layout.main_activity to setContentView().

TextView mTextView;

// some transient state for the activity instance
String mGameState;

public void onCreate(Bundle savedInstanceState) {
    // call the super class onCreate to complete the creation of activity like
    // the view hierarchy

    // recovering the instance state
    if (savedInstanceState != null) {
        mGameState = savedInstanceState.getString(GAME_STATE_KEY);

    // set the user interface layout for this Activity
    // the layout file is defined in the project res/layout/main_activity.xml file

    // initialize member TextView so we can manipulate it later
    mTextView = (TextView) findViewById(R.id.text_view);

// This callback is called only when there is a saved instance previously saved using
// onSaveInstanceState(). We restore some state in onCreate() while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
public void onRestoreInstanceState(Bundle savedInstanceState) {

// invoked when the activity may be temporarily destroyed, save the instance state here
public void onSaveInstanceState(Bundle outState) {
    out.putString(GAME_STATE_KEY, mGameState);
    out.putString(TEXT_VIEW_KEY, mTextView.getText());

    // call superclass to save any view hierarchy

You can create new objects in your activity code and build a view hierarchy by inserting new Views into a ViewGroup. You then use that layout by passing the root ViewGroup to setContentView(). To get further information about creating a user interface, you can see the User Interface documentation.

Your activity does not reside in the Created state. The activity enters the Started State, after the onCreate() method finishes execution. Then, the system calls the onStart() and onResume() methods in quick succession. The next section explains the onStart()callback.

  • onStart()

The system demands this callback, when the activity enters the Started state. In order to make the activity visible to the user, you can use the onStart()call as the app prepares for the activity to enter the foreground and become interactive.

Besides, it also registers a BroadcastReceiver that monitors changes that are reflected in the UI. The activity does not stay resident in the Started state, the onStart() method completes very quickly and, as with the Created state. The activity will enter the Resumed state, once this callback finishes, and the system invokes the onResume()method.

  • onResume()

The onResume() system invokes the callback, when the activity enters the Resumed state. The system will once again calls as onResume() method, if the activity returns to the Resumed state from the Paused state. For this reason, to initialize components that you release during onPause(), you should implement onResume(). For example, you may initializa the camera as follows:

public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Get the Camera instance as the activity achieves full user focus
    if (mCamera == null) {
        initializeCamera(); // Local method to handle camera init

Furthermore, to initialize components that you release during onPause(), you should implement onResume(). Then, perform any other initializations that must occur each time the activity enters the Resumed state.

  • onPause()

To pause operations such animations and music playback that should not continue while the Activity is in the Paused state, and that you expect to resume shortly. There are several reasons why an activity may end up in this state:

  • A new, semi-transparent activity (such as a dialog) opens. As long as the activity is still     partially visible but not in focus, it remains paused.
  • Some event interrupts app execution, as described in the onResume() This is the most common case.
  • In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode. Because only one of the apps (windows) has focus at any time, the system pauses all of the other apps.

For example, the onPause()method is a good place to release it, if your application uses the camera. The following example of onPause() is the same to the  onResume() example above, releasing the camera that the  onResume() example initialized.

public void onPause() {
    super.onPause();  // Always call the superclass method first

    // Release the Camera because we don’t need it when paused
    // and other activities might need to use it.
    if (mCamera != null) {
        mCamera = null;

  • onStop()

The Stopped state is when your activity is no longer visible to the user and the system invokes the onStop()callback. You can also call your activity as onStop() when the activity has finished running, and is about to be terminated. Below is how an implementation of onStop() that saves the contents of a draft note to persistent storage:

protected void onStop() {
    // call the superclass method first

    // save the note’s current draft, because the activity is stopping
    // and we want to be sure the current note progress isn’t lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());

    // do this update in background on an AsyncQueryHandler or equivalent
    mAsyncQueryHandler.startUpdate (
            mToken,  // int token to correlate calls
            null,    // cookie, not used here
            mUri,    // The URI for the note to update.
            values,  // The map of column names and new values to apply to them.
            null,    // No SELECT criteria are used.
            null     // No WHERE columns are used.

  • OnDestroy()

This is the final call that the activity receives. Usually this activity exists due to someone’s calling  finish(), or because the system is temporarily destroying the process containing the activity to save space.

The system may also call this method when an orientation change occurs, and then immediately call onCreate() to recreate the process in the new orientation.

 Activity State and Ejection from Memory

Instead the system kills an activity directly; it kills the process in which the activity runs, destroying not only the activity but also everything else running in the process, as well. Basically, when it needs to free up the RAM, the system will kill process. Moreover, a user can also kill a process by using the Application Manager under Settings to kill the corresponding app.

Table 1 shows the correlation among process state, activity state, and likelihood of the system’s killing

Likelihood of being killed Process state Activity state
Least Foreground (having or about to get focus) Created
More Background (lost focus) Paused
Most Background (not visible) Stopped
Empty Destroyed