'Spring QuerydslPredicate - exception handling for bad types
I didn't find any proper solution for this so maybe you can assist. Basically issue is ultra simple I want to do some kind of "better looking" error handling when using QuerydslPredicate
I have entity where ID is of Number format (on database side) - on entity level its private Long id.
And here come my problem while fetching everything in normal (expected scenarios like):
- /testEndpoint&pageSize=100&id=1
- /testEndpoint&pageSize=100&id=1123123
All work great. But when I enter non numeric value to id like id=randomTest I got NumberFormatException
@GetMapping
public ApiResponsePage listTest(
@RequestParam(defaultValue = "0") final Integer pageNo,
@RequestParam(defaultValue = "10") final Integer pageSize,
@RequestParam(defaultValue = "id") final String sortBy,
@QuerydslPredicate(root = TestEntity.class) final Predicate predicate
) {
final Page<TestEntity> all = testEntityRepo.findAll(predicate);
return all;
}
Case is that this exception is thrown on parsing level so its not even reaching testEntityRepo.findAll(predicate);. Is there any way to handle such exceptions in more "elegant" way ? So I can put some custom message etc ?
Log:
INFO 18388 --- [ main] d.v.s.a.s.e.DefaultExceptionReporter : GET /testEndpoint caused Failed to convert from type [java.lang.String] to type [@javax.persistence.Id java.lang.Long] for value 'testRandomValue'; nested exception is java.lang.NumberFormatException: For input string: "testRandomValue"
Solution 1:[1]
The one option is to make exceptionHandler:
@ExceptionHandler(ConversionFailedException.class)
public ResponseEntity conversionFailedException(ConversionFailedException ex) {
return ResponseEntity
.badRequest()
.contentType(APPLICATION_JSON_UTF8)
.body(createResponseBody(ex.getMessage()));
}
This is working, but its taking all errors of this type so if you have any other place where it appear it can be overhead
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user2188158 |