javax.ws.rs.ext.ExceptionMapper提供了可以进行异常处理的接口类
public interface ExceptionMapper<E extends Throwable> {
Response toResponse(E var1);
}
系统中已经包含的处理实现类:
使用注解@Service @Provider声明实现上节接口的实现类,同时重写toResponse方法,参考实现如下:
public Response toResponse(Throwable throwable) {
if (throwable instanceof Error) {
this.dealPrintError(throwable);
} else if (!(throwable instanceof ErrorCodeException) && !(throwable instanceof I18nException) && !(throwable instanceof I18nArrayException)) {
if (throwable instanceof RuntimeException) {
this.dealPrintRuntimeException(throwable);
} else {
this.dealPrintOtherException(throwable);
}
} else {
this.dealPrintI18nException(throwable);
}
if (this.customMapper != null) {
return this.customMapper.toResponse(throwable);
} else {
try {
return this.mapper(throwable);
} catch (Throwable var4) {
LOG.error("map failed", var4);
ExceptionResult result = this.mapperForErrorCodeException(new ErrorCodeException(this.DEFAULT_ERROR_CODE));
return Response.ok(result, "application/json").status(this.DEFAULT_STATUS).build();
}
}
}
其中针对系统内置的异常进行定制的额外处理,如
this.dealPrintI18nException(throwable);
最后通过引入自定义的异常处理扩展点,原理是通过配置文件指导具体类,并反射加载实例化,填充
private ExceptionMapper super Throwable> customMapper;
最终构造对象 ExceptionResult返回
return Response.ok(result, "application/json").status(result.getHttpStatus()).build();
参考:https://github.com/sunquan291/error-code-fill
<groupId>com.zte.sdn.oscpgroupId>
<artifactId>error-code-spring-boot-starterartifactId>
<version>2.4.4version>
@GetMapping(value = "/list")
public MultiResponse<ATAMetricCO> test() {
return MultiResponse.buildFailure("00000001", "error xxx");
}
{
"errcodes":[
{"code":"00000001","level":"ERROR","label":"Error occurred in server."}
]
}
{"errCode":"00000001","errMessage":"Error occurred in server.","success":false}