多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 代码 如下,spring默认帮我们处理的异常,很不靠谱.需要我们自己去写. ~~~ package com.like.domain; public class Item { private Integer id; private String name; private Double price; @Override public String toString() { return "Item{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } } ~~~ ~~~ package com.like.service; import com.like.domain.Item; import org.springframework.stereotype.Service; import java.util.Random; @Service public class ItemService { public Item saveItem(Item item) { int id = new Random().nextInt(100); item.setId(id); return item; } } ~~~ ~~~ package com.like.controller; import com.like.domain.Item; import com.like.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/item") public class ItemController { @Autowired private ItemService itemService; @PostMapping("/show") public ResponseEntity<Item> saveItem(Item item) { if (item.getPrice() == null){ throw new RuntimeException("价格不能为空"); } return ResponseEntity.status(HttpStatus.CREATED).body(itemService.saveItem(item)); } } ~~~ ## 结果 ![](https://box.kancloud.cn/6b846a754522c808c168b55f25e03b1d_2022x970.png) ## 返回异常 创建CommonExceptionHandler类. ~~~ package com.like.advice; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice //默认情况下它会自动拦截所有的@controller注解的类.注意,要保证这个类能被启动类扫描到并防区容器中 public class CommonExceptionHandler { @ExceptionHandler(RuntimeException.class) //拦截的异常类型 public ResponseEntity<String> handleException(RuntimeException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); } } ~~~ ## 结果 ![](https://box.kancloud.cn/8cc01eba8e1e55d9271efbfec153d423_1546x762.png) ## 自定义异常类