我有一个用java(springboot)编写的restapi,我的请求从请求头获取一个json字符串(不要问为什么这样:),例如,{flowerid:123}在我的控制器中,我将字符串Map到对象。因此,当用户传入垃圾数据时,例如{flowerid:},就会抛出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;
1条答案
按热度按时间7qhs6swi1#
异常处理程序无效。你的方法
processServletRequestBindingException()
声明ServletRequestBindingException
异常作为参数,但为@ExceptionHandler(value = {JsonMappingException.class})
. 此异常类型必须兼容,否则将无法工作,并且在异常处理过程中会出现异常。new ObjectMapper().readValue()
两个都扔JsonParseException
以及JsonMappingException
. 两者都延伸JsonProcessingException
因此,您很可能需要此异常的处理程序来处理这两种情况:请注意,最好使用autowire
ObjectMapper
从spring上下文中删除,并且不创建新示例。