mem*_*und 13 java spring spring-mvc spring-web
我有一个简单的web服务,可以返回内容json为plain text(或取决于客户端的accepthttp标头).
问题:如果在text/plain请求期间发生错误,Spring会以某种方式返回a 406 Not Acceptable.这有点不对,因为spring也可以将错误写为普通错误文本,而且应该绝对保留400错误状态:
@RestController
public class TestServlet {
@PostMapping(value = "/test", produces = {APPLICATION_JSON_VALUE, TEXT_PLAIN_VALUE, "text/csv"})
public Object post() {
throw new BadRequestException("bad req");
}
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String msg) {
super(msg);
}
}
Run Code Online (Sandbox Code Playgroud)
POST请求accept=application/json:
{
"timestamp": "2018-07-30T14:26:02",
"status": 400,
"error": "Bad Request",
"message": "bad req",
"path": "/test"
}
Run Code Online (Sandbox Code Playgroud)
但是accept=text/csv(或text/plain)显示带状态的空响应406 Not Acceptable.
我也注意到它DispatcherServlet.processDispatchResult()被调用了两次:首先是我的BadRequest异常,第二次是HttpMediaTypeNotAcceptableException.很明显,我的自定义异常的渲染失败了,但为什么呢?