4

我有一个用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;
4

1 回答 1

0

您的异常处理程序无效。您的方法将异常processServletRequestBindingException()声明ServletRequestBindingException为参数,但注释为@ExceptionHandler(value = {JsonMappingException.class}). 此异常类型必须兼容,否则将不起作用,并且在异常处理期间会出现异常。

new ObjectMapper().readValue()抛出JsonParseExceptionJsonMappingException。两者都扩展JsonProcessingException,因此您很可能需要此异常的处理程序来涵盖两种情况:

@ExceptionHandler(JsonProcessingException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public GetFlowerResponse handleJsonProcessingException(
        HttpServletRequest req, JsonProcessingException ex) {
   ...
}

请注意,最好ObjectMapper从 Spring 上下文中自动装配,不要创建新实例。

于 2018-12-11T23:57:51.180 回答