Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return HTTP error status code *and* content in Struts2

Tags:

java

struts2

I have a Controller that receives accepts http file uploads and responds with a JSON confirmation. If there is is any sort of problem with the procsessing of the upload I want to return an HTTP error status code (e.g. 403 for malformed requests or 500 for a general processing error), but I also want to send a JSON list of detailed error messages. I know how to return a 500 error (thanks to this post) but I don't know how to return the 500 code and still send content.

Here's a snippit of my code (which doesn't do what I want it to):

@Action(value = "upload", results = { 
  @Result(name = SUCCESS, type = "freemarker", location = "results.ftl", params = { "contentType", "text/plain" }), 
  @Result(name = ERROR, type = "freemarker", location = "error.ftl", params = { "contentType", "text/plain" }), 
  @Result(name = ERROR, type = "httpheader", params = { "status", "500" }) 
})

public String upload() {
  //do stuff
  if(CollectionUtils.isEmpty(getActionErrors()) {
    return SUCCESS;
  } else {
     return ERROR;
  }
}
like image 669
NobodyMan Avatar asked Oct 27 '25 09:10

NobodyMan


1 Answers

This is an old post, but if you are using the Struts-JSON which I suggest using you can simply return an error object with what you want and attach the status code like below:

@Result(name = ERROR, type="json", 
        params = {"root","errorResponse", "statusCode", "500"}
)   
like image 116
Ty Danielson Avatar answered Oct 29 '25 22:10

Ty Danielson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!