如何在Spring REST异常处理程序中设置响应文本?

Ala*_*n47 5 java rest spring httpresponse

我正在使用Spring REST控制器,特别是在异常处理程序上。异常处理程序按预期工作,并且我的JUnit-Test(使用Spring HTTP客户端)显示在客户端接收到正确的HTTP状态代码(400)。HTTP客户端会自动将其转换为HttpClientErrorException

但是,HttpClientErrorException始终打印总是为我产生以下结果:

HttpClientErrorException: 400 null

... null部分是让我担心的。这不是服务器端异常的消息应该存在的地方吗?

我检查了HTTP客户端的源代码,以查看客户端异常在何处引发。看起来像这样:

throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response));

调试此调用后发现这response.getStatusText()就是null我的情况。

我的问题是:如何ResponseEntity在服务器端进行设计,以使HTTP客户端找到服务器端的异常消息response.getStatusText()而不是null

我的当前看起来像这样:

@ExceptionHandler({ MyCustomException.class })
public ResponseEntity<String> handleException(final HttpServletRequest req, final MyCustomException e) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-type", "text/plain");
    String body = e.toString();
    return new ResponseEntity<>(body, headers, HttpStatus.BAD_REQUEST);
}
Run Code Online (Sandbox Code Playgroud)

...,然后输入null客户端状态文本。

Ala*_*n47 4

我必须承认我在这件事上被愚弄了。nullSpring 打印的值HttpClientErrorExceptionstatusText. 此文本是静态的。例如,对于状态代码 404,定义的状态文本为“未找到”。没有办法改变它。

为了接收实际的异常代码,那么Utku建议的方法是完全正确的。小问题是错误消息需要从 中提取HttpClientErrorException#getResponseBodyAsString(),而不是HttpClientErrorException#getStatusText()像我尝试的那样。