Skip to content
Advertisement

How to construct a custom JSON error response using the Struts 2 framework

I am working on creating a web application using Struts 2. I want to send out JSON error response like the below when the request URL is not well formed:

{
  “status”: 409,
  "code": 40924
  “property”: “aggregation”,
  “message”: “aggregationId not specified.”,
  “moreInfo”: “https://www.iiitb-swn.com/docs/api/errors/40924”
} 

I am already using the struts2-json plugin for serializing response objects using JSON. How should I go about sending JSON error responses. I can think of the below way of doing the same.

Use an error response object in the action class and set all name required name value pairs explicitly

private Map<String, String> errorObject;

public String execute()
{
    ...
    if (aggregationId == -1)
    {
        errorObject = new HashMap<>();
        errorObject.put("status", "400");
        errorObject.put("code", "40924");
        ...
        return INPUT;
    }
    ...
}

I could then handle serializing only the errorObject in my struts.xml.

I am wondering if there is an established way of doing this? Perhaps one which makes using of the Struts 2 framework better.

Advertisement

Answer

Struts2 actionErrors, fieldErrors provided by the ActionSupport. You can fill action errors or they are produced by the validation interceptor. For example

addFieldError("aggregation", “aggregationId not specified.”);
addFieldError("moreInfo", “https://www.iiitb-swn.com/docs/api/errors/40924”);

Then return json result as a response.

<result name="input" type="json">
  <param name="statusCode">409</param>
  <param name="errorCode">40924</param>
  <param name="ignoreHierarchy">false</param>
  <param name="includeProperties">^actionErrors.*,^fieldErrors.*</param>
</result> 
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement