Java 返回找不到方法的错误响应正文-spring rest webservice

Java 返回找不到方法的错误响应正文-spring rest webservice,java,spring,web-services,rest,spring-boot,Java,Spring,Web Services,Rest,Spring Boot,我们正在为我们的应用程序使用spring boot。我们有一个rest控制器,它有许多方法,其中一种方法如下所示 @RequestMapping(value = "/accounts/{id}/cards", produces = "application/json; charset=utf-8", method = RequestMethod.GET) @ResponseBody public String getCards(@PathVariable("id") String id) thr

我们正在为我们的应用程序使用spring boot。我们有一个rest控制器,它有许多方法,其中一种方法如下所示

@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,而不返回正文


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

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

@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);
    }
}
@ControllerAdvice
公共类RestExceptionHandler扩展了ResponseEntityExceptionHandler{
@ExceptionHandler(值={HttpRequestMethodNotSupportedException.class})
受保护的ResponseEntity handleConflict(RuntimeException ex,WebRequest请求){
String bodyOfResponse=“这应该是特定于应用程序的”;
返回手柄内部(例如,响应主体,
新建HttpHeaders(),HttpStatus.CONFLICT,请求);
}
}

来源:

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);
    }
}
@ControllerAdvice
公共类RestExceptionHandler扩展了ResponseEntityExceptionHandler{
@ExceptionHandler(值={HttpRequestMethodNotSupportedException.class})
受保护的ResponseEntity handleConflict(RuntimeException ex,WebRequest请求){
String bodyOfResponse=“这应该是特定于应用程序的”;
返回手柄内部(例如,响应主体,
新建HttpHeaders(),HttpStatus.CONFLICT,请求);
}
}

来源:

问题是“什么是最简单的方法”。没有指定问题。问题是它为不同的请求提供了不同的状态代码,如果方法类型为DELETE,则返回405,如果方法类型为LINK,则返回501,我想知道如何获得带有错误体的常见代码。为什么您希望更少的描述性响应代码这是我的团队的决定,有一个共同的方法说身体不允许使用方法。问题是“什么是最简单的方法”。没有指定问题。问题是它为不同的请求提供了不同的状态代码,如果方法类型为DELETE,则返回405,如果方法类型为LINK,则返回501,我想知道如何获得带有错误体的常见代码。为什么您希望更少的描述性响应代码这是我的团队的决定,有一个共同的方法,说方法不允许与身体。