在 Controller 层对系统作防御性编程

简介

Web 开发中无论是 MVC 还是 DDD 架构 Controller 层都是系统的门面,既对外的接口,对内的接口,一般情况下任何错误必须组织在 Controller 层

如何作

在 Controller 层中的接口使用 try-catch

复制代码
@Slf4j
@RestController("/")
@RequiredArgsConstructor
public class TestController {

    private final TestRepository testRepository;

    @GetMapping
    public Response<String> index() {
        try {
            testRepository.save();
            return new Response<>();
        } catch (Exception e) {
            return new Response<>();
        }
    }
}

另外为避免前端和后端相互干扰我们还应积极使用 dto 、entity 、PO对象

复制代码
public Response<List<MonitorDataMapDTO>> queryMonitorDataMapEntityList() {
        try {
            List<MonitorDataMapEntity> monitorDataMapEntities = logAnalyticalService.queryMonitorDataMapEntityList();
                 doEntityToDto()
            }
            return Response.<List<MonitorDataMapDTO>>builder()
                    .code("0000")
                    .info("调用成功")
                    .data(monitorDataMapDTOS)
                    .build();
        } catch (Exception e) {
            return Response.<List<MonitorDataMapDTO>>builder()
                    .code("0001")
                    .info("调用失败")
                    .build();
        }
    }

    @RequestMapping(value = "draw", method = RequestMethod.POST)
    @Override
    public Response<ActivityDrawResponseDTO> draw(@RequestBody ActivityDrawRequestDTO request) {
        try {
            if (doCheckParameter()) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }

            UserRaffleOrderEntity orderEntity = raffleActivityPartakeService.thisMethodWillQueryEntityByRequestId()
    
            return something();

        } catch (AppException e) {
         
             return something();

        } catch (Exception e) {
            return something();
        }
    }
相关推荐
自强的小白2 小时前
核心功能(Service接口)
java·mybatis
乌暮3 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习
大猫和小黄3 小时前
深入理解 Java Optional:从设计哲学到工程实战
java
数据库百宝箱4 小时前
rum&gin索引对比
java·数据库·gin
yychen_java4 小时前
第六篇:Spring AI 实战:将 Java 业务接口封装成企业级 MCP Server
java·人工智能·spring
_upupup4 小时前
异常(C++)
java·开发语言·jvm
g10565591394 小时前
公有云_云运维服务
java·运维·服务器
霸道流氓气质4 小时前
ComfyUI 图像生成工作流完全指南:从节点编排到Java生产级图像生产实战
java·开发语言·人工智能
再写一行代码就下班5 小时前
linux sh脚本在windows修改导致无法使用解决方式
java·linux·centos