spring boot 404错误自定义错误响应ReST

新手上路,请多包涵

我正在使用 Spring Boot 来托管 REST API。我不想使用标准错误响应,而是希望始终发送 JSON 响应,即使浏览器正在访问 URL 以及自定义数据结构也是如此。

对于自定义异常,我可以使用 @ControllerAdvice 和 @ExceptionHandler 来做到这一点。但是对于 404 和 401 等标准错误和已处理错误,我找不到任何好的方法来执行此操作。

有什么好的模式可以做到这一点吗?

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

阅读 670
1 个回答

对于那些不想使用 @EnableWebMvc 的 Spring Boot 2 用户

应用程序.properties

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

控制器通知

@RestControllerAdvice
public class ExceptionResolver {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public HashMap<String, String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) {
        HashMap<String, String> response = new HashMap<>();
        response.put("status", "fail");
        response.put("message", e.getLocalizedMessage());
        return response;
    }
}

资源

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

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