Spring REST

时间:2017-08-08 09:34:25

标签: spring-mvc 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,或者可能在异常中的任何其他信息。 (虽然我承认它对测试系统的调试非常有用。)

如何防止将此详细信息发送到客户端? (理想情况下仍然保持它在我们的测试系统上的表现。)

2 个答案:

答案 0 :(得分:2)

我最近遇到了同样的问题,我建议你尝试这种方式:

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

}

答案 1 :(得分:1)

您可以定义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