chen.lin
昨天 b003a49794f49a329e2702918ecfc8d14b371d0d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> 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;
    }
}