在 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();
        }
    }
相关推荐
:1211 天前
java基础
java·开发语言
曹牧1 天前
Spring:@RequestMapping注解,匹配的顺序与上下文无关
java·后端·spring
daixin88481 天前
cursor无法正常使用gpt5.5等模型解决方案
java·redis·cursor
韦禾水1 天前
记录一次项目部署到tomcat的异常
java·tomcat
曦月合一1 天前
树莓派安装jdk、tomcat、vnc、谷歌浏览器开机自启等环境配置
java·tomcat·树莓派
此剑之势丶愈斩愈烈1 天前
openssl 自建证书
java
面汤放盐1 天前
何时使用以及何时不应使用微服务:没有银弹
java·运维·云计算
0xDevNull1 天前
Spring Boot 自动装配:从原理到实践
java·spring boot·后端
qq_589568101 天前
java学习笔记,包括idea快捷键
java·ide·intellij-idea
小怪吴吴1 天前
idea 开发Android
android·java·intellij-idea