在 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();
        }
    }
相关推荐
Zane19947 小时前
HashSet、TreeSet、LinkedHashSet:底层都是"套壳"
java·后端
相顾若初见8 小时前
RuoYi后端jar镜像制作
java·jar
MacroZheng8 小时前
程序员看文档神器,装上它,看Spring官方文档就一目了然了!
java·人工智能·后端
深漂的华哥8 小时前
Ruoyi-Vue-Plus(V5.6.2) 开发环境搭建
java·前端·spring boot·后端·spring·ruoyi
wanger618 小时前
AI应用开发知识点总结
java
Escalating_xu8 小时前
【C++ vector 深度解析】从常用接口、扩容机制与迭代器失效到核心模拟实现
java·c++·面试
今天AI了吗8 小时前
AI 数据安全治理框架:模型能力与数据权限的边界在哪里
java·linux·开发语言·人工智能·python·深度学习·机器学习
LCG元8 小时前
【实战】树莓派物联网开发:DHT11温湿度采集与MQTT云上报全流程
java·jvm·物联网
斯内普吖8 小时前
(开源)农产品电商系统实战指南 基于 Java + SpringBoot + Vue + MySQL
java·vue.js·spring boot·mysql·开源
SimonKing8 小时前
AI逆向实战:一个壁纸网站被我5分钟摸透了,你也能
java·后端·程序员