Himanshu Yadav
Himanshu Yadav

Reputation: 13585

REST: Handling the 400 error for GET requests

I have a GET request url entities\{id}. Here RestController is expecting id in a Long format.
Test case says that if user passes an invalid id, controller should return a HTTP-400 Bad Request error. For example: /entities/21.0, /entities/xx etc.
But before hitting the controller itself jersey is throwing a HTTP-404 error.

RestController looks like this:

@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getEntityById(@PathParam("id") Long id){}

Upvotes: 0

Views: 323

Answers (1)

DwB
DwB

Reputation: 38300

Caveat: This is not a great solution, but it is an functioning solution.

First: I believe @PathVariable is the correct annotation, not @PathParam (I'm reading the 3.2 spring reference).

  1. Change the type of the id parameter to String
  2. in the method do a Long.parseLong(id) and catch the NumberFormatException.
  3. Return the desired error indication for the NumberFormatException.

Upvotes: 1

Related Questions