Error recovery with Google Cloud Endpoints

I have an endpoint generated as follows:

public Book insertBook(Book book) {
    PersistenceManager mgr = getPersistenceManager();
    try {
        if (containsShout(book)) {
            throw new EntityExistsException("Object already exists");
        }
        mgr.makePersistent(book);
    } finally {
        mgr.close();
    }
    return book;
}

I wonder how I should return errors to the client. For instance. the book contains some required fields, ISNM verification, etc.

So, I would assume that I would throw an exception, but how will this appear in json's answer. The json response must contain all field errors in order to highlight these fields in the client.

+5
source share
3 answers

In general, exceptions respond to the 500 http status code in the response. With the following exceptions, you can get different codes: com.google.api.server.spi.response.BadRequestException→ 400 com.google.api.server.spi.response.UnauthorizedException→ 401 com.google.api.server.spi.response.ForbiddenException→ 403 com.google.api.server.spi.response.NotFoundException→ 404

Android, IOException, , catch.

+5

- , , .

class Response<T> {
   Status status; 
   String userFriendlyMessage;
   T object; //your bean or entity object

   RestResponse toRestResponse() {
      RestResponse r = new RestResponse();
      r.status = status;
      r.userFriendlyMessage = userFriendlyMessage;
      r.object = object;
   }
}

. RestResponse, Response.

class RestResponse {
   Status status;
   String userFriendlyMessage;
   Object object;
}

.

public enum Status {
   SUCCESS, RESOURCE_NOT_FOUND, RESOURCE_ALREADY_EXISTS; //etc
}

endpoint RestResponse, , , Response (T bean ).

json (RestResponse) .

, .

, Sathya

+3

Entity.

It has a ResponseCode, which is an enumeration and String ErrorMessage.

So, the "Book" can be inherited from Entity. And your answer might look like this:

public Book insertBook(Book book) {
    PersistenceManager mgr = getPersistenceManager();
    try {
        if (containsShout(book)) {
            book.setResponseCode(ResponseCode.ERROR);
            book.setError("Object already exists");
        } else {
            mgr.makePersistent(book);
        }
    } finally {
        mgr.close();
    }
    return book;
}
0
source

All Articles