1 全局异常捕获处理类
@ControllerAdvice + @ExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理所有不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail("操作失败!");
return response;
}
/**
* 处理所有业务异常 自定义异常
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
}
2 dubbo服务异常
provider端抛出异常,consumer捕获并处理异常
使用dubbo提供的自定义异常类 RpcException作为抛出的异常, consumer端进行捕获处理
provider 抛出异常
try{
count = dao.insert(ao);
}catch(DuplicateKeyException e){
//抛出rpcException 传递给消费端
throw new RpcException(int_code,string_msg);
}
consumer端 捕获
try {
result = service.registeredUser(entity);
}catch (RpcException e){
log.error(e.getCode() + e.getMessage());
}