我有一个用Java编写的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;
答案 0 :(得分:0)
您的异常处理程序无效。您的方法processServletRequestBindingException()
声明了ServletRequestBindingException
作为参数的异常,但为@ExceptionHandler(value = {JsonMappingException.class})
添加了注释。此异常类型必须兼容,否则将无法正常工作,并且您将在异常处理期间收到异常。
new ObjectMapper().readValue()
会同时抛出JsonParseException
和JsonMappingException
。两者都扩展JsonProcessingException
,因此您很可能需要针对此异常的处理程序来涵盖两种情况:
@ExceptionHandler(JsonProcessingException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public GetFlowerResponse handleJsonProcessingException(
HttpServletRequest req, JsonProcessingException ex) {
...
}
请注意,最好从Spring上下文自动装配ObjectMapper
,并且不要创建新实例。