正如 Shaunak Patel 所指出的,处理此问题的方法是自定义错误处理程序。有很多方法可以实现一个,但是一个简单的实现让你得到你想要的结果是这样的
@RestControllerAdvice
public class ControllerAdvice {
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Map<String, Object> handleConstraintViolationException(HttpRequestMethodNotSupportedException ex) {
Map<String, Object> response = new HashMap<>();
response.put("timestamp", Instant.now().toEpochMilli());
response.put("status", HttpStatus.METHOD_NOT_ALLOWED.value());
response.put("error", HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
response.put("exception", ex.getClass().getName());
response.put("message", String.format("Request method '%s' not supported", ex.getMethod()));
return response;
}
}
一个curl 命令来说明
$ curl -v -X POST 'localhost:8080/testproject/datasets12/'
{
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"error": "Method Not Allowed",
"message": "Request method 'POST' not supported",
"timestamp": 1554400755087,
"status": 405
}