4

自定义 grails 域约束验证失败返回的默认错误对象的最佳方法是什么?

我得到的当前 JSON 是

{"errors": [{"object": "com.self.learning.grails.demo.api.Person", 
    "field": "name",
    "rejected-value": "K12332434",
    "message": "Property [orgKey] of class [class com.self.learning.grails.demo.api.Person] with value [K123324343432432432432] exceeds the maximum size of [12]"
}]}

我想从上述响应中删除“对象”,并希望拥有“错误代码”。

我对 grails 很陌生,并且在一些基本的实现上苦苦挣扎。提前致谢。

4

2 回答 2

2

您可以为验证错误创建一个新的自定义编组器并将其注册Bootstrap.groovy

JSON.registerObjectMarshaller( new MyCustomValidationErrorsMarshaller() )

只需将此行替换为您error-code的示例:

json.property( "error-code", HttpStatus.UNPROCESSABLE_ENTITY.value() )

一种快速的方法是在引导程序中注册对象编组器,但这会使引导程序类膨胀。编写自定义编组器更简洁。

另一种方法是编写一个拦截器拦截响应object,然后用您想要的错误代码替换错误响应。

于 2015-12-31T18:27:51.887 回答
0

您可以编写自己的类并用您想要的数据填充它。还可以考虑包括您可能需要的其他数据

您可以使用的示例 BaseException:

public class BaseException extends Exception {
    static def userService
    //import org.apache.commons.logging.LogFactory
    private static final log = LogFactory.getLog(this)

    private int status ;
    private String devMessage;
    private String extendedMessage;
    private String moreInfo;
    private int errorCode;
    boolean error = true;

    public BaseException(int status,int errorCode,String message, String extendedMessage ,String moreInfo){
        this.errorCode = errorCode;
        this.status = status;
        this.devMessage = message;
        this.extendedMessage = extendedMessage;
        this.moreInfo = moreInfo;
    }

    public JSONObject errorResponse(){
        JSONObject errorJson = new JSONObject();
        errorJson.put("status",this.status);
        errorJson.put("errorCode",this.errorCode);
        errorJson.put("message",this.devMessage);
        errorJson.put("extendedMessage",this.extendedMessage);
        errorJson.put("error",error);
        errorJson.put("dateTimeStamp", new Timestamp(new Date().time).toString());
        return errorJson;
    }

    public static BaseException createBaseException(String jsonStr) {
        try {
            def json = new JsonSlurper().parseText(jsonStr)
            return new BaseException(json["status"],json["errorCode"],json["message"], json["extendedMessage"] ,json["moreInfo"])
        } catch (Exception ex) {
            return null
        }
    }
}
于 2015-12-30T22:33:17.413 回答