【问题标题】:Return an error response body for method not found - spring rest webservice返回未找到方法的错误响应正文 - spring rest webservice
【发布时间】:2016-03-23 05:35:00
【问题描述】:

我们正在为我们的应用程序使用 Spring Boot。我们有一个休息控制器,它有很多方法,其中一种方法如下所示

@RequestMapping(value = "/accounts/{id}/cards", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
@ResponseBody
public String getCards(@PathVariable("id") String id) throws JsonMappingException, IOException

如果这个url有GET以外的其他请求,例如它为不同的请求给出不同的状态码,如果方法类型是DELETE它返回405,如果它是LINK类型它返回501没有body。

如何返回带有错误正文的常见状态码 405?

【问题讨论】:

  • 问题是'什么是最简单的方法'。不指定问题。
  • 问题是它为不同的请求提供不同的状态码,如果方法类型是 DELETE,它返回 405,如果它是 LINK 类型,它返回 501,我想看看我怎样才能得到一个带有错误正文的通用代码
  • 为什么您需要较少描述性的响应代码
  • 这是我团队的决定,采用一种通用方法,即 Method Not Allowed with body。

标签: java spring web-services rest spring-boot


【解决方案1】:

Spring 支持全局 @ExceptionHandler 和新的 @ControllerAdvice 注释

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler{

    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

来源:Check here for more detail

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多