本文介绍了如何抑制 Spring 启动错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

团队,

Spring boot 抛出错误响应 405(Correct response),但出于安全原因,错误消息应该被抑制并带有 out path 消息.

The Spring boot throws error response 405(Correct response),but due to security reason the error message should be suppressed with out path message.

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

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

Help me to solve the issue by returning the response without path message.

推荐答案

正如 Shaunak Patel 所指出的,处理此问题的方法是自定义错误处理程序.有很多方法可以实现,但一个简单的实现就是这样

As pointed out by Shaunak Patel, the way to handle this is a custom error handler. There are plenty of ways to implement one, but a simple implementation getting you the result you want is something like this

@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
}

这篇关于如何抑制 Spring 启动错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 06:35