spring-boot - 如何抑制 Spring Boot 错误消息
问题描述
团队,
Spring boot 抛出错误响应 405(正确响应),但由于安全原因,错误消息应该被抑制,没有路径消息。
{
"timestamp": 1554394589310,
"status": 405,
"error": "Method Not Allowed",
"exception":
"org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/testproject/datasets12/"
}
通过返回没有路径消息的响应来帮助我解决问题。
解决方案
正如 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
}
推荐阅读
- c++ - C++:打印 unicode 字符
- java - Spring Rest - 发布多个文件
- mysql - MySQL INNER JOIN 返回一行,但从前端,它显示没有行
- reactjs - ComponentDidMount 看不到父母的道具
- selenium - Chrome 无法启动:崩溃。来自 crontab
- amazon-ec2 - 在安全组规则中使用安全组作为源时是否可以匹配公共 IP?
- flutter - Keyboard hiding my bottom sheet text field in flutter
- excel - 包含特定字符串的文件名复制内容并根据找到的字符串添加具有特定值的列
- angular - 角度传递变量到函数调用
- javascript - How to properly work with promises, Firebase and React's UseEffect hook?