我有一个 Spring Boot 应用程序,目前正在使用 mvnw spring-boot:run
运行它
我已经设置了一个自定义异常,如下所示
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class InvalidEntityException extends Exception {
public InvalidEntityException() {
super();
}
public InvalidEntityException(String message) {
super(message);
}
public InvalidEntityException(String message, Throwable cause) {
super(message, cause);
}
public InvalidEntityException(Throwable cause) {
super(cause);
}
}
在休息 Controller 中的方法中,我可以抛出此异常,并且在 Spring Boot 日志中我可以看到
已解决[foo.bar.InvalidEntityException:错误消息。]
在 JSON 响应中我的数据如下所示:
error: "Bad Request"
message: "Error message"
path: "/resource/request"
status: 400
timestamp: "2021-06-06T04:12:39.759+00:00"
但是,当我运行 mvn clean package
并使用 java -jar out.jar
运行输出 .jar 文件并调用此 Controller 上的方法时,我不再看到消息 Resolved [foo.bar.InvalidEntityException: Error message.]
并且我的 JSON 响应如下所示,但缺少消息。
error: "Bad Request"
message: ""
path: "/resource/request"
status: 400
timestamp: "2021-06-06T04:12:39.759+00:00"
从 mvnw spring-boot:run
运行 springboot 应用程序与运行 .jar 有什么区别?我想要解决错误消息的相同行为
最佳答案
我怀疑您正在使用 Spring Boot 的 devtools 模块。它旨在使应用程序开发更容易,并且在将应用程序作为打包的 jar 运行时会自动禁用。
Devtools 将 spring.mvc.log-resolved-exception 设置为 true
。这会导致记录Resolved [foo.bar.InvalidEntityException: Error message.]
。
Devtools 还将 server.error.include-message
设置为 ALWAYS
。这会导致异常消息包含在错误响应中。在非开发环境中,应谨慎设置该属性。您需要确保应用程序的任何异常消息都不会泄露您不希望恶意客户端看到的信息。
关于java - 打包的 Spring boot 应用程序无法将其余 api 错误解析为消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67855743/