在 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();
        }
    }
相关推荐
橙淮5 小时前
并发编程(六)
java·jvm
拽着尾巴的鱼儿5 小时前
springboot openfeign 自定义feign 接口重试机制
java·spring boot·后端
白露与泡影5 小时前
2026大厂Java面试题大全!牛客网最新版
java·开发语言
EntyIU6 小时前
JVM内存与GC笔记
java·jvm·笔记
XS0301066 小时前
并发编程 六
java·后端
yaoxin5211236 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
雪宫街道6 小时前
synchronized 锁的范围:对象锁、类锁与代码块锁
java·jvm·后端·面试
x***r1516 小时前
linux安装 jdk-8u291-linux-x64.tar.gz 详细步骤(解压配置环境变量)
java
极光代码工作室7 小时前
基于SpringBoot的校园论坛系统
java·springboot·web开发·后端开发
XS0301067 小时前
Spring Bean 作用域 & 生命周期
java·后端·spring