如何使用 Struts 2 框架构建自定义 JSON 错误响应 [英] How to construct a custom JSON error response using the Struts 2 framework
问题描述
我正在使用 Struts 2 创建 Web 应用程序.当请求 URL 格式不正确时,我想发送如下 JSON 错误响应:
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"
}
我已经在使用 struts2-json 插件来使用 JSON 序列化响应对象.我应该如何发送 JSON 错误响应.我可以想到以下方法来做同样的事情.
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;
}
...
}
然后我可以只处理我的 struts.xml
中的 errorObject
序列化.
I could then handle serializing only the errorObject
in my struts.xml
.
我想知道是否有一种既定的方法来做到这一点?也许是一种可以更好地使用 Struts 2 框架的方法.
I am wondering if there is an established way of doing this? Perhaps one which makes using of the Struts 2 framework better.
推荐答案
Struts2 actionErrors
, fieldErrors
由 ActionSupport
提供.您可以填写操作错误,或者它们由验证拦截器生成.例如
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");
然后返回 json
结果作为响应.
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>
这篇关于如何使用 Struts 2 框架构建自定义 JSON 错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!