# 异常统一处理

# 基于magic-api实现

与自定义JSON统一结果一样,都需要实现ResultProvider

@Component
public class MyResultProvider implements ResultProvider {

	@Override
	public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
		long timestamp = System.currentTimeMillis();
        return new JsonBean<>(code, message, data, (int) (timestamp - requestEntity.getRequestTime()));
	}

	@Override
	public Object buildException(RequestEntity requestEntity, Throwable throwable) {
		return buildResult(requestEntity, 500, "系统内部出现错误");
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 基于Spring实现

与原有方式一样,自己实现全局异常统一处理,随后将magic-api的异常处理交给spring

magic-api:
  throw-exception: true # 执行出错时,异常将抛出处理
1
2
上次更新: 8/31/2021, 1:06:51 PM
赞助商