Graphil 3 Setting the error object

What is the best way to configure the default error object returned with grails county constraint validation errors?

The current JSON I get is

{"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]"
}]}

I want to get rid of the “object” from the above answer and want to have an “error code”.

I am new to grails and struggling with a few basic implementations. Thanks in advance.

+4
source share
2 answers

You can create a new custom marshaller for validation errors and register it Bootstrap.groovyas

JSON.registerObjectMarshaller( new MyCustomValidationErrorsMarshaller() )

Just replace this line with yours error-code, for example:

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

- , . .

interceptor , object .

+2

. ,

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
        }
    }
}
0

Source: https://habr.com/ru/post/1621811/


All Articles