too*_*ive 5 java api rest spring exceptionhandler
我有一个用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;
Run Code Online (Sandbox Code Playgroud)
您的异常处理程序无效。您的方法将异常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) {
...
}
Run Code Online (Sandbox Code Playgroud)
请注意,最好ObjectMapper从 Spring 上下文自动装配并且不要创建新实例。