如何使用Struts框架构造自定义错误json响应 [英] How to construct a custom error json response using the Struts framework

查看:216
本文介绍了如何使用Struts框架构造自定义错误json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用struts创建一个Web应用程序。我想在请求URL格式不正确时发出如下所示的错误JSON响应

I am working on creating a web application using struts. I want to send out a error JSON 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的新手,并想知道是否有一种既定的方法可以做到这一点?也许更好地使用Struts框架。

I am new to Struts and was wondering if there is an established way of doing this? Perhaps one which makes using of the Struts 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框架构造自定义错误json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆