DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Trending

  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • Rust, WASM, and Edge: Next-Level Performance
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • Monolith: The Good, The Bad and The Ugly

Error Handling in APIKit-based Projects

By 
Ross Mason user avatar
Ross Mason
·
Mar. 26, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
15.8K Views

Join the DZone community and get the full member experience.

Join For Free

[This article was originally written by Eugene Berman.] 

error handlingIf you look at the W3C document listing HTTP status codes, you may notice that only a small portion of all possible codes represents the happy path – i.e. 2xx codes. Most other codes are there to let client know that something went wrong with the request and the expected response cannot be returned. When building an APIKit-based application, developers must properly handle error conditions and set status codes accordingly. As always with Mule, there are many ways to achieve that. Let’s look at some of them.

Our use case is a very simple ACME Company API which returns a product information based on a particular product ID. In other words,

GET /products/{id}

Our RAML is as follows:

#%RAML 0.8
---
title: Acme REST API
version: v0.1
baseUri: http://localhost:8081/acme/{version}
          
/products/{id}:
    displayName: Product    
    get:
      description: Get Product by ID
      responses:
        200:
          body:
            text/plain:

When we create a new APIKit project in Studio and add a RAML file, it generates flows for each RESTful call. In our case, it will produce one flow which handles our request:

<flow name="get:/products/{id}:acme-config" doc:name="get:/products/{id}:acme-config">
    <set-payload value="#[NullPayload.getInstance()]" doc:name="Set Payload"/>
</flow>

We can now replace the default content of this flow with a business logic that queries the database and returns product information:

<flow name="get:/products/{id}:acme-config" doc:name="get:/products/{id}:acme-config">
    <jdbc-ee:outbound-endpoint exchange-pattern="request-response" queryKey="GetProductByID" queryTimeout="-1" doc:name="Database">
        <jdbc-ee:query key="GetProductByID" value="SELECT * FROM Products WHERE ID=#[flowVars['id']]"/>
    </jdbc-ee:outbound-endpoint>
    <!-- add transformation logic here -->
</flow>

But what if our query returns no results? From the JDBC transport perspective, this is not an error condition – the returned payload will simply be an empty list. In this case, our API call will return an empty response, with the HTTP status code 200 – something the client would expect. Or, if our transformation logic expects some data from the database, it may fail, throwing an exception – again, not the desired behavior. What we really need is to return status 404 and potentially some object containing more details. All we need is to add a <choice> message processor, e.g.:

<choice>
	<when expression="#[payload.size != 0]">
		<!-- Add processing logic here -->
	</when>
	<otherwise>
		<set-property propertyName="http.status" value="404"/>
		<set-payload value="Quoth the server, 404"/>
	</otherwise>
</choice>

How about any other scenarios where something else may go wrong? Wouldn’t it be great if we had an exception strategy which can automatically map exceptions to response codes?

Let’s look at our generated code again. There’s a new global element called apikit:mapping-exception-strategy:

    <apikit:mapping-exception-strategy name="acme-apiKitGlobalExceptionMapping">
        <apikit:mapping statusCode="404">
            <apikit:exception value="org.mule.module.apikit.exception.NotFoundException" />
            <set-property propertyName="Content-Type" value="application/json" />
            <set-payload value="{ "message": "Resource not found" }" />
        </apikit:mapping>
        <apikit:mapping statusCode="405">
            <apikit:exception value="org.mule.module.apikit.exception.MethodNotAllowedException" />
            <set-property propertyName="Content-Type" value="application/json" />
            <set-payload value="{ "message": "Method not allowed" }" />
        </apikit:mapping>
        <apikit:mapping statusCode="415">
            <apikit:exception value="org.mule.module.apikit.exception.UnsupportedMediaTypeException" />
            <set-property propertyName="Content-Type" value="application/json" />
            <set-payload value="{ "message": "Unsupported media type" }" />
        </apikit:mapping>
        <apikit:mapping statusCode="406">
            <apikit:exception value="org.mule.module.apikit.exception.NotAcceptableException" />
            <set-property propertyName="Content-Type" value="application/json" />
            <set-payload value="{ "message": "Not acceptable" }" />
        </apikit:mapping>
        <apikit:mapping statusCode="400">
            <apikit:exception value="org.mule.module.apikit.exception.BadRequestException" />
            <set-property propertyName="Content-Type" value="application/json" />
            <set-payload value="{ "message": "Bad request" }" />
        </apikit:mapping>
    </apikit:mapping-exception-strategy>

It allows mapping exception types to status codes, content types, error messages and anything else you may want to return as a part of your error response. You can add as many mappings as you need, however, you will have to either know all types of exceptions at the design time (which is not always possible) or throw a specific exception using Java or scripting component, e.g.:

<scripting:component>
    <scripting:script engine="groovy">
        <![CDATA[
	    throw new org.mule.module.apikit.exception.NotFoundException("Product ID does not exist!"); 
	]]>
    </scripting:script>
</scripting:component>

In reality, a combined approach should be used. Use as much logic as possible to gracefully handle some error conditions, use mapping exception strategy to intercept and map other errors.

Now you can finish your ACME API, connect it to a database of your choice and send the request for a product that does not exist in the database.

Quoth the server, 404…

Published at DZone with permission of Ross Mason, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!