内部错误,在 Spring REST 中返回给客户端的调试信息过多

Internal error, too much debug info returned to client, in Spring REST

如果在我的 Spring REST 代码中抛出异常,服务器会向客户端发送类似于以下内容的内容:

{
  "timestamp": 1502184648199,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.foo.DataAccessException",
  "message": "SQL [select * from my_table]: Table does not exist",
  "path": "/my-api"
}

我担心如果在实时系统上以这种方式安装,客户端会暴露太多内部信息。它可能包含 SQL 指示我们的 table 结构,或可能在异常中的任何其他信息。 (尽管我承认它对在测试系统上进行调试很有用。)

如何防止将这些详细信息发送给客户? (理想情况下,它在我们的测试系统上仍然保持这种行为。)

您可以定义您的 ExceptionHandler 来定义异常情况下的自定义响应格式。只需定义 ExceptionHandler 并覆盖默认响应格式。 示例代码:

    @ExceptionHandler({ Exception.class })
public ResponseEntity<Object> handleAll(Exception ex, WebRequest request) {
    ApiError apiError = new ApiError(
      HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "error occurred");
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}

看看Custom Error message spring rest

我最近也遇到了同样的问题,建议你这样试试:

https://blog.jdriven.com/2016/06/spicy-spring-custom-error-json-response-with-errorattributes/

@Component
@Slf4j
public class MyCustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);

        if(LOGGER.isDebugEnabled()){

            Throwable throwable = getError(requestAttributes);
            if(throwable!=null) {
                Throwable cause = throwable.getCause();
                if (cause != null) {
                    Map<String, Object> causeErrorAttributes = new HashMap<>();
                    causeErrorAttributes.put("exception", cause.getClass().getName());
                    causeErrorAttributes.put("message", cause.getMessage());
                    errorAttributes.put("cause", causeErrorAttributes);
                }
            }
        }else{
            errorAttributes.remove("message");
            errorAttributes.remove("exception");
        }
        return errorAttributes;
    }

}