JAVA-异常与错误码机制

异常机制
  • 核心异常类:PendingException,较其它异常增加了错误码的属性。
  • 原则上从service,web层的方法调用中,不允许抛出其它非运行时异常,需要将之转换为PendingException
  • 在某些父类中有将异常转化为PendingException的方法
 protected PendingException toPendingException(Exception ex, ResBean sysFailedResBean, String message) {
        // 当是PendingException时的处理
        if (ex instanceof PendingException) {
            PendingException pendingException = (PendingException) ex;
            error("操作异常:错误码 = " + pendingException.getCode() + " , 错误信息 = " + pendingException.getMessage());
            return pendingException;
            // 其它异常的处理
        } else {
            error("操作异常:" + message, ex);
            return sysFailedResBean.toException(message);
        }
    }
  • 事务中的调用必须要捕获异常,并手动设置回滚
    @Override
    @RpcMethod("更新商品自定义信息")
    public void updateGoodsSelfDef(@RequestBody GoodsSelfDefUpdateRequest request) throws PendingException {
        validateThrow(request);
        newTransactionTemplate.execute(status -> {
            try {
                // 1.更新商品信息
                Goods sql = Goods.builder()
                        .aliasName(request.getAliasName())
                        .efficacy(replaceSemicolon(request.getEfficacy()))
                        .searchKeywords(addSemicolon(request.getSearchKeywords()))
                        .build();
                if(CollectionUtils.isNotEmpty(request.getGuaranteeCodes())) {
                    sql.setGuarantees(String.join(",", request.getGuaranteeCodes()));
                }
                if(!sql.isAllFiledsNull()) {
                    sql.setId(request.getGoodsId());
                    goodsFacade.update(sql);
                }
                // 2.更新商品分类信息
                updateCategoryGoods(request.getStoreId(), request.getGoodsId(), request.getCategoryIds());
                // 3.更新商品标签信息
                updateTagGoods(request.getStoreId(), request.getGoodsId(), request.getGoodsTagIds());
                // 3.更新商品活动图片信息
                commonProfFacade.updateAttachmentList(AttachmentRequest.builder()
                        .businessId(request.getGoodsId())
                        .businessType(BusinessType.GOODS_SPECIAL)
                        .attachmentList(request.getGoodsSpecialImages())
                        .build());
                // 清除缓存
                goodsCache.clearCache(request.getGoodsId());
                return Boolean.TRUE;
            } catch (Exception ex) {
                status.setRollbackOnly();
                error("商品信息更新失败", ex);
                throw toRpcRuntime(ex);
            }
        });
    }

转载于:https://www.cnblogs.com/wuyuhuanzhen/p/11014325.html

你可能感兴趣的:(JAVA-异常与错误码机制)