package com.vincent.rsf.openApi.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.Map; /** * 自定义错误属性:响应体中不返回 path(仅打印日志);保证业务异常信息写入 message 返回给前端。 */ @Component public class CustomErrorAttributes extends DefaultErrorAttributes { private static final Logger log = LoggerFactory.getLogger(CustomErrorAttributes.class); private static final String KEY_PATH = "path"; private static final String KEY_MESSAGE = "message"; @Override public Map getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map attrs = super.getErrorAttributes(webRequest, options); Object path = attrs.remove(KEY_PATH); if (path != null) { log.warn("Error path: {}", path); } // 保证业务异常信息返回给前端(如 CoolException) Throwable error = getError(webRequest); if (error != null && error.getMessage() != null && !error.getMessage().isEmpty()) { attrs.put(KEY_MESSAGE, error.getMessage()); } return attrs; } }