简体   繁体   中英

Restful Services: Sending HTTP 405 instead of HTTP 500 error

There are two issues:
Issue 1:
When user does not send any request payload for one of the POST api call. Its corresponding RestController method, processes the incoming request and throws a null pointer exception. It sends back HTTP 500 error code and stack trace as the error description.
HTTP 405 is expected to be return here.

@POST
@Path("/create")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response createEntity(MyEntity entity) 
{
 EntityRequest req = new EntityRequest();
 req.setName(entity.getName());//throws NPE here
 //few more lines to send req to backend and get the response back
 return response;
}


Issue 2:
There is GET request API implementation.

@GET
@Path("/entity/{entityId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON})
public Response findMyEntityById(
        @PathParam("entityId") String id) 
{
  EntityRequest req = new EntityRequest();
  //similar stuff and sends the response back
  return response;
}

Issue is if user hit the http://localhost:8080/entities/entity/12 and sends a POST request instead of GET . API should throw 405 but it is throwing 500 right now. Actual stack trace:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException and MIME media type application/octet-stream was not found

The first case is clear. 405 means "Method Not Allowed". It is typically thrown by container or framework if specific URL cannot reply to request of current method. But you do use correct method but with empty body that causes NPE in your code. In this case 500 status is expected.

Issue 2 is not clear. You should send more details. You either do not send POST or the URL can accept POST. Please double check and send details about your configuration, some code snippets etc.

EDIT:

after posting some code I can say that GET request cannot consume anything. Remove @Consumes({ MediaType.APPLICATION_JSON }) from findMyEntityById() . Try it. If it helps you can say that it is a kind of bug in Jersey: it actually should either throw exception during deployment that GET cannot consume anything or ignore @Consume if GET method is processed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM