如何抑制Spring Boot错误消息

时间:2019-04-04 16:23:57

标签: spring-boot

团队,

Spring引导会引发错误响应405(正确响应),但由于安全原因,应使用路径错误消息来抑制错误消息。

{
"timestamp": 1554394589310,
"status": 405,
"error": "Method Not Allowed",
"exception": 
"org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/testproject/datasets12/"
}

通过返回不带路径消息的响应来帮助我解决问题。

1 个答案:

答案 0 :(得分:3)

正如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
}
相关问题