在 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 小时前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
白鲸开源2 小时前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
用户298698530146 小时前
Java 实现 Word 文档文本查找与高亮标注
java·后端
宇宙之一粟7 小时前
乐企版式文件生成平台
java·后端·python
plainGeekDev8 小时前
MVC 写法 → MVVM
android·java·kotlin
SL_staff8 小时前
3周搭完MES系统:JVS低代码+JVS-IoT物联网的实战记录
java·前端·低代码
MacroZheng8 小时前
斩获20w star!Claude Code最强插件,AI编程必备!
java·人工智能·后端
唐青枫10 小时前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
小bo波1 天前
使用Thread子类创建线程 VS 使用Runnable接口创建线程的区别
java·多线程·thread·并发编程·runnable
SamDeepThinking1 天前
高并发场景下,CompletableFuture与ForkJoinPool该如何取舍?
java·后端·面试