spring-boot - 在 Spring Boot 中返回响应消息
问题描述
我正在使用带有 h2 数据库的 spring boot。我想在成功插入寄存器时返回 201 消息,在复制时返回 400 消息。我正在使用 ResponseEntity 来实现这一点,例如,接下来是我从服务中创建的方法:
@Override
public ResponseEntity<Object> createEvent(EventDTO eventDTO) {
if (eventRepository.findOne(eventDTO.getId()) != null) {
//THis is a test, I am looking for the correct message
return new ResponseEntity(HttpStatus.IM_USED);
}
Actor actor = actorService.createActor(eventDTO.getActor());
Repo repo = repoService.createRepo(eventDTO.getRepo());
Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
eventRepository.save(event);
return new ResponseEntity(HttpStatus.CREATED);
}
这是我的控制器:
@PostMapping(value = "/events")
public ResponseEntity addEvent(@RequestBody EventDTO body) {
return eventService.createEvent(body);
}
但是我在浏览器中没有收到任何消息,我正在与邮递员进行不同的测试,当我咨询所有事件时,结果是正确的,但每次我发帖时,我都没有在浏览器中收到任何消息,我不太确定这个问题的原因是什么。有任何想法吗?
解决方案
好的,我真的觉得发送ResponseEntity
但不发送的服务不太好Controller
。您可以在这些情况下使用@ResponseStatus
和ExceptionHandler
类,如下所示。
exception
在包中创建一个类
GlobalExceptionHandler.java
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(DataIntegrityViolationException.class) // NOTE : You could create a custom exception class to handle duplications
public void handleConflict() {
}
}
控制器.java
@PostMapping(value = "/events")
@ResponseStatus(HttpStatus.CREATED) // You don't have to return any object this will take care of the status
public void addEvent(@RequestBody EventDTO body) {
eventService.createEvent(body);
}
现在改变服务看起来像,
服务.java
@Override
public void createEvent(EventDTO eventDTO) { // No need to return
if (eventRepository.findOne(eventDTO.getId()) != null) {
throw new DataIntegrityViolationException("Already exists"); // you have to throw the same exception which you have marked in Handler class
}
Actor actor = actorService.createActor(eventDTO.getActor());
Repo repo = repoService.createRepo(eventDTO.getRepo());
Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
eventRepository.save(event);
}
推荐阅读
- excel - 从 Access 中提取数据时,Export-Excel 返回不可读的结果
- python-3.x - sklearn_crfsuite 中的 AttributeError 没有属性 CRF 错误
- slack - 为什么我的 Slack 机器人名称不接受更新?
- c# - 为什么这两个功能没有并行执行
- cuda - cudaMemcpy 返回成功但不复制任何内容
- javascript - While 循环在 P5.js 的函数中不起作用
- xpath - XPath 选择器在 XPath Helper 控制台中有效,但在 scrapy 中无效
- mysql - Mysql“写”命令列表,或者如何判断一个mysql命令是否涉及写操作
- c++ - 有什么方法可以为 std::pair 声明 operator[] 吗?
- vba - 使用 VBA 根据 Access 中的日期组合框从表中创建搜索表单