如何向Spring MVC REST服务添加错误?

时间:2013-06-07 14:02:28

标签: json spring rest spring-mvc

如果用户没有输入我编码的两个名称,如何更改/更新以下来自Spring MVC的REST调用以返回错误...类似于未找到的?

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
    @ResponseBody
    public User getName(@PathVariable String name, ModelMap model)
    {

        logger.debug("I am in the controller and got user name: " + name);

        /*

            Simulate a successful lookup for 2 users, this is where your real lookup code would go

         */

        if ("name2".equals(name))
        {
            return new User("real name 2", name);
        }

        if ("name1".equals(name))
        {
            return new User("real name 1", name);
        }


        return null;
    }

2 个答案:

答案 0 :(得分:10)

定义一个新的异常类,例如ResourceNotFoundException并从带注释的控制器方法getName中抛出一个实例。

然后还在Controller类中定义一个带注释的异常处理程序方法来处理该异常,并返回404 Not Found状态代码,可能会记录它。

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public void handleResourceNotFoundException(ResourceNotFoundException ex)
{
    LOG.warn("user requested a resource which didn't exist", ex);
}

甚至使用@ResponseBody注释返回一些错误消息:

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public String handleResourceNotFoundException(ResourceNotFoundException ex)
{
    return ex.getMessage();
}

答案 1 :(得分:2)

您可以专门为返回错误响应创建一个对象。这样,你可以说任何你想要的。例如:

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ResponseStatus> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex){

    ResponseStatus responseStatus = new ResponseStatus("400", "Bad Request. " + ex);
    responseStatus.setResponseStatusTime(timestampService.createTimestamp());
    HttpStatus status = HttpStatus.BAD_REQUEST;

    ResponseEntity<ResponseStatus> response = new ResponseEntity<ResponseStatus>(responseStatus, status);

    return response;
}

在此示例中,您可以看到有一个ResponseStatus对象。该对象包含状态代码,状态消息,日期和时间的字段。您可能不需要日期和时间,但我发现当有人向我发送他们看到的错误时,它很有用,因为这样很容易在我们的服务器日志中准确找到它发生的位置。