上面的这些异常信息我们可以加入一些自定义的内容 ```java @Configuration public class CustomerConfig {
@Bean public CustomerErrorAttribute customerErrorAttribute(){
return new CustomerErrorAttribute(true);
}
}
```java
public class CustomerErrorAttribute extends DefaultErrorAttributes {
/**
* 最大栈元素
*/
private final int MAX_STACK_TRACE_ELEMENT = 5;
public CustomerErrorAttribute(boolean includeException) {
super(includeException);
}
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> result = super.getErrorAttributes(webRequest, includeStackTrace);
Throwable throwable = super.getError(webRequest);
try {
// 增加exception相关的信息,用来在通过feign调用的客户端进行反序列化,实现feign rpc的异常处理
List<StackTraceElement> steList = new LinkedList<>();
for(StackTraceElement stackTraceElement : throwable.getStackTrace()) {
steList.add(stackTraceElement);
if(steList.size() >= MAX_STACK_TRACE_ELEMENT) {
break;
}
}
throwable.setStackTrace(steList.toArray(new StackTraceElement[steList.size()]));
result.put("message","勇士总冠军");
result.put("exception_detail", JSONObject.toJSONString(throwable));
result.put("author","gaoxi");
result.put("phone","18751669318");
} catch (Exception e) {
e.setStackTrace(new StackTraceElement[0]);
result.put("exception_detail", e);
}
return result;
}
}
- 自定义异常信息后