spring-boot - Spring Boot Exception 不显示原因/描述
问题描述
我想通过 Spring Boot 中的一个描述性异常并且包含一个原因,即。“找不到狗”。目前我得到了异常,但它是通用的:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Apr 20 09:32:07 CEST 2021
There was an unexpected error (type=Not Found, status=404).
@Service 方法实现抛出错误:
@Service
public class DogServiceImpl implements DogService {
@Autowired
DogRepository dogRepository;
public String retrieveDogBreedById(Long id){
Optional<String> optionalBreed = Optional.ofNullable(dogRepository.findBreedById(id));
String breed = optionalBreed.orElseThrow(DogNotFoundException::new);
return breed;
};
这是我的例外:
@ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Dog not found")
public class DogNotFoundException extends RuntimeException{
public DogNotFoundException() {
}
public DogNotFoundException(String message) {
super(message);
}
}
我正在将 @RestController 用于 REST API
解决方案
错误处理 Spring Boot Starter可以很容易地做到这一点。有关快速概述,请参阅https://foojay.io/today/better-error-handling-for-your-spring-boot-rest-apis/或https://wimdeblauwe.github.io/error-handling-spring- boot-starter/获取完整文档。
如果你只是DogNotFoundException
在这样定义时抛出:
@ResponseStatus(value= HttpStatus.NOT_FOUND)
public class DogNotFoundException extends RuntimeException{
public DogNotFoundException() {
super("Dog not found");
}
public DogNotFoundException(String message) {
super(message);
}
}
,那么库将默认确保以下响应:
{
"code":"DOG_NOT_FOUND",
"message":"Dog not found"
}
(免责声明:我是图书馆的作者)
推荐阅读
- php - PHP文件:如何开始一个新行
- ruby-on-rails - 使用变量重定向到子域(Ruby on Rails)
- java - 在 web.xml 的 cookie 配置中设置时,最近的浏览器不会强制执行安全标志
- java - 类继承具有私有构造函数的 Builder Pattern 类
- node.js - NODEJS 如何获取 gifsicle 中的路径输入?
- regex - 我需要使用正则表达式从以下阶段获取金额值
- javascript - JSON 中位置 0 的意外令牌 - REST API(节点和快递)
- google-cloud-platform - 无法使用 terraform 在 gcp 中运行 startup_script
- windows-shell - IFileOperation:如何判断一个文件夹的重命名是否与另一个文件夹合并?
- python - 在遍历 ndarray 时访问相邻列中的元素