I have a rest api written in Java (spring boot), my request takes a json string from request header(do not ask why this way:), e.g. {flowerId: 123} In my controller, I map the string to object. So when users pass in junk data, e.g. {flowerId: abc}, JsonMappingException will be thrown. I'd like to handle the exception in my exception handler but unable to catch it in my handler. Did I miss something? thanks
See my code below.
@RestController
public class FlowerController {
@GetMapping
@ResponseStatus(HttpStatus.OK)
public GetFlowerResponse getFlowers(@RequestHeader(name = Constants.myHeader) String flowerIdString) throws IOException {
GetFlowerRequest getFlowerRequest = new ObjectMapper().readValue(flowerIdString, GetFlowerRequest.class);
//get Flower info with request ...
}
}
@RestControllerAdvice
public class ApplicationExceptionHandler {
@ExceptionHandler(value = {JsonMappingException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public GetFlowerResponse processServletRequestBindingException(HttpServletRequest req, ServletRequestBindingException e) {
return buildExceptionResponse(e, ErrorMessages.INVALID_REQUEST.getCode(), e.getMessage());
}
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public GetFlowerResponse processUnhandledExceptions(HttpServletRequest req, Exception e) {
return buildExceptionResponse(e, ErrorMessages.SERVICE_UNAVAILABLE.getCode(), ErrorMessages.SERVICE_UNAVAILABLE.getDescription());
}
}
public class GetFlowerRequest {
int flowerId;
}
public class GetFlowerResponse {
private List<ReturnDetail> returnDetails;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReturnDetail {
@Builder.Default
private Integer code = 0;
@Builder.Default
private String message = "";
private String source;