自定义SpringBoot REST API 404返回信息

自定义SpringBoot REST API 404返回信息

在访问SpringBoot的REST接口时,如果请求的地址不存在Spring会返回如下JSON信息

{
  "timestamp": 1492063521109,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/restapi/xxx"
}

我们可以通过实现ErrorController来定制化返回的JSON,例子如下:

@RestController
public class RestNotFoundFilter implements ErrorController {

    private static final String NOT_FOUND = "404";
    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public RestResponse handleError() {
        RestResponse response = new RestResponse();
        response.setCode(NOT_FOUND);
        response.setMessage("Request resource not found.");
        return response;
    }

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

}

示例代码中的RestResponse是一个通用返回体Java bean,自己定义.

posted on 2017-10-20 11:27  IceWee  阅读(8932)  评论(0编辑  收藏  举报

导航