使用Spring MVC,接受带有错误JSON的POST请求会导致返回默认的400错误代码服务器页面

2022-09-03 13:54:52

我正在开发一个 REST API。收到带有错误JSON的POST消息(例如{sdfasdfasdf})会导致Spring返回400错误请求错误的默认服务器页面。我不想返回页面,我想返回自定义 JSON 错误对象。

当使用@ExceptionHandler引发异常时,我可以执行此操作。因此,如果它是一个空白请求或空白JSON对象(例如{}),它将抛出一个NullPointerException,我可以使用我的 ExceptionHandler捕获它并做任何我想做的事情。

那么问题来了,当Spring只是无效的语法时,它实际上并没有抛出异常......至少不是我能看到的。它只是从服务器返回默认的错误页面,无论是Tomcat,Glassfish等。

所以我的问题是,我如何“拦截”Spring并导致它使用我的异常处理程序或以其他方式阻止错误页面显示并返回JSON错误对象?

这是我的代码:

@RequestMapping(value = "/trackingNumbers", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public ResponseEntity<String> setTrackingNumber(@RequestBody TrackingNumber trackingNumber) {

    HttpStatus status = null;
    ResponseStatus responseStatus = null;
    String result = null;
    ObjectMapper mapper = new ObjectMapper();

    trackingNumbersService.setTrackingNumber(trackingNumber);
    status = HttpStatus.CREATED;
    result = trackingNumber.getCompany();


    ResponseEntity<String> response = new ResponseEntity<String>(result, status);

    return response;    
}

@ExceptionHandler({NullPointerException.class, EOFException.class})
@ResponseBody
public ResponseEntity<String> resolveException()
{
    HttpStatus status = null;
    ResponseStatus responseStatus = null;
    String result = null;
    ObjectMapper mapper = new ObjectMapper();

    responseStatus = new ResponseStatus("400", "That is not a valid form for a TrackingNumber object " + 
            "({\"company\":\"EXAMPLE\",\"pro_bill_id\":\"EXAMPLE123\",\"tracking_num\":\"EXAMPLE123\"})");
    status = HttpStatus.BAD_REQUEST;

    try {
        result = mapper.writeValueAsString(responseStatus);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    ResponseEntity<String> response = new ResponseEntity<String>(result, status);

    return response;
}

答案 1

这是作为Spring SPR-7439的一个问题提出的 - JSON(杰克逊)@RequestBody编组抛出尴尬的异常 - 这在Spring 3.1M2中通过让Spring在消息正文丢失或无效的情况下抛出a来修复。org.springframework.http.converter.HttpMessageNotReadableException

在你的代码中,你不能创建一个,因为它是抽象的,但我用一个更简单的方法在本地测试了这个异常,在Jetty 9.0.3.v20130506上运行Spring 3.2.0.RELEASE。ResponseStatus

@ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String resolveException() {
    return "error";
}

我收到了400状态“错误”字符串响应。

这个缺陷在春季论坛的帖子中进行了讨论。

注意:我开始使用Jetty 9.0.0.M4进行测试,但是有一些其他内部问题阻止了完成,因此根据您的容器(Jetty,Tomcat,其他)版本,您可能需要获得一个较新版本,该版本可以很好地与您正在使用的任何版本的Spring配合使用。@ExceptionHandler


答案 2