自定义异常处理
异常统一处理
serviceComb提供了统一的异常处理入口,可以添加自定义异常解析
如果是多个项目通用的可以写到common项目中。
- 添加自定义异常或者使用依赖中提供的都可以,这里已RuntimeException为示例
添加异常类 PlatformException 继承 RuntimeException
- 在代码中加入异常处理
public xxxx....{
try {
xxxxx....
} catch (Exception e) {
throw new PlatformException("xxxxxx");
}
xxxxx....
}
- 添加异常处理
创建CloudPlatformExceptionToProducerResponseConverter异常处理类,implements接口ExceptionToProducerResponseConverter
泛型T 就是你要捕获的异常类
public class CloudPlatformExceptionToProducerResponseConverter implements ExceptionToProducerResponseConverter<PlatformException> {
private static final Logger logger = LoggerFactory.getLogger(CloudPlatformExceptionToProducerResponseConverter.class);
/**
* 异常处理顺序
*/
private static final int ORDER = 1;
@Override
public Class<PlatformException> getExceptionClass() {
return PlatformException.class;
}
@Override
public Response convert(SwaggerInvocation swaggerInvocation, PlatformException e) {
logger.error(ExceptionUtil.getMessage(e));
String url = ((Invocation)swaggerInvocation).getRequestEx().getRequestURI();
logger.info("throw PlatformException error...........url....." + url);
logger.info("throw PlatformException error...........context....." + ((Invocation) swaggerInvocation).getContext().toString());
BaseRespResult baseRespResult = BaseRespResult.errorResult(e.getErrorCode(), e.getErrorParam(), e.getErrorMsg());
InvocationException state = new InvocationException(javax.ws.rs.core.Response.Status.OK, baseRespResult);
logger.error("log.isErrorEnabled():{}", logger.isErrorEnabled());
logger.info("log.isInfoEnabled():{}", logger.isInfoEnabled());
e.printStackTrace();
//这行代码是将异常信息保存到平台的异常日志中
CloudExceptionInfoStorage.saveExceptionLog(url,((Invocation) swaggerInvocation).getRequestEx().getParameterMap(),baseRespResult.getMessage(),baseRespResult.getCode(),e.getStackTrace());
return Response.succResp(baseRespResult);
}
@Override
public int getOrder() {
return ORDER;
}
}
- 配置文件添加异常引用,不然不生效
打开自己的项目(这里我截图meta,只是举例,并不是说要放到meta中),在注入异常处理配置文件中添加新添加的Converter
最后编辑: 于春辉 文档更新时间: 2024-11-08 17:00 作者:于春辉