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

时间:2015-12-16 22:01:58

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

我们正在为我们的应用程序使用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

如果除了GET之外还有对此URL的任何其他请求,例如它为不同的请求提供不同的状态代码,如果方法类型为DELETE,则返回405,如果它是LINK类型,则返回501而没有正文。

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

1 个答案:

答案 0 :(得分:3)

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