我有一个用Java(spring boot)编写的rest api,我的请求从请求头中获取一个json字符串(不要问为什么这样:),例如{flowerId:123}在我的控制器中,我将字符串映射到对象。所以当用户传入垃圾数据时,例如{flowerId:abc},就会抛出JsonMappingException。我想在我的异常处理程序中处理异常,但无法在我的处理程序中捕获它。我错过了什么?谢谢
请参阅下面的代码。
@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;