How to create a custom json error response using the Struts structure

I am working on creating a web application using struts. I want to send a JSON error message as shown below when the request URL is not formed correctly.

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

I already use the struts2-json plugin to serialize response objects using JSON. How should I send JSON error responses. I can think about how to do the same.

Use the error response object in the action class and explicitly specify all pairs of names whose names are explicitly specified

private Map<String, String> errorObject;

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

Then I could only handle serialization errorObjectin mine struts.xml.

I'm new to Struts and wondered if there is an established way to do this? Perhaps the one that uses the Struts structure better.

+4
2

Struts2 actionErrors, fieldErrors ActionSupport. , .

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

json .

<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> 
+2

"fieldErrors" .

, ( )

@Result(name="input", type="json", params={"root","fieldErrors"})

ajax success JSON

success : function(fieldErrors, textStatus, jqXHR) {
        for (var property in fieldErrors) {
            if (fieldErrors.hasOwnProperty(property)) {
                var this_field_err = fieldErrors[property];
                $('#submit_result').append(property+" error");
                for(var ix=0; ix<this_field_err.length; ix++) {
                    $('#submit_result').append(this_field_err[ix]);
                    $('#submit_result').append("<br>"); 
                }
            }
        }
    }

div #submit_result

username error: Username must be at least 6 charachers long
password error: Password msut be at least 8 charachers long 
+1

All Articles