0

I have an JaxRS API like this :

@GET
@Path("list") 
public Response list(@QueryParam("id") Long id) {
...
}

How can i handle exception when send non digits parameter as id ?
actually i can not found any validation annotation on JakartaEE framework for handle this problem .
example request :

curl http://localhost:8080/api/list?id=ABCD       

NOTE: I won't change Long to String .

mah454
  • 1,571
  • 15
  • 38

2 Answers2

2

You should add validate annotation after @QueryParam:

@GET
@Path("list") 
public Response list(@QueryParam("id")
                     @Min(value=0L, message="insert number value") 
                     Long id) {
...
}
N3tMaster
  • 398
  • 3
  • 13
0

Finally i catch that exception.

first of all:
I try to handle this problem with this annotations :

@Min
@PositiveOrZero
@Pattern(regexp = "\\[0-9]+") or @Pattern(regexp = "\\d+")
@Digits
... 

None of them worked, Because that string must first be converted into a number and then validated. so JaxRs could not do that !
I used this solution:

@Provider
public class NumberExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(Exception exception) {
        Exception numberFormatException = getNumberFormatException(exception);
        if (numberFormatException != null) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Invalid Parameter").build();
        } else {
            return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
        }
    }

    private Exception getNumberFormatException(Exception e) {
        if (e instanceof NumberFormatException nfe) return nfe;
        return getNumberFormatException((Exception) e.getCause());
    }
}  

Worked without any problem .
Thank you .

mah454
  • 1,571
  • 15
  • 38