Spring Boot 禁用/错误映射

新手上路,请多包涵

我正在使用 Spring Boot 创建 API,因此希望禁用 /error 映射。

我在 application.properties 中设置了以下道具:

 server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

然而,当我点击 /error 我得到:

 HTTP/1.1 500 Internal Server Error
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 03 Aug 2016 15:15:31 GMT
Connection: close

{"timestamp":1470237331487,"status":999,"error":"None","message":"No message available"}

要求的结果

HTTP/1.1 404 Internal Server Error
Server: Apache-Coyote/1.1

原文由 ptimson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

您可以禁用 ErrorMvcAutoConfiguration :

 @SpringBootApplication
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class SpringBootLauncher {

或者通过 Spring Boot 的 application.yml/properties:

 spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

如果这不适合您,您也可以使用自己的实现扩展 Spring 的 ErrorController:

 @RestController
public class MyErrorController implements ErrorController {

    private static final String ERROR_MAPPING = "/error";

    @RequestMapping(value = ERROR_MAPPING)
    public ResponseEntity<String> error() {
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    }

    @Override
    public String getErrorPath() {
        return ERROR_MAPPING;
    }

注意: 使用上述技术 _之一_(禁用自动配置或实施错误控制器)。如评论中所述,两者一起 不起作用

原文由 alexbt 发布,翻译遵循 CC BY-SA 4.0 许可协议

应通过@SpringBootApplication 指定属性。 Kotlin 中的示例:

 @SpringBootApplication(exclude = [ErrorMvcAutoConfiguration::class])
class SpringBootLauncher {

原文由 kejm 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题