2

如果用户没有输入我正在编码的两个名称,我如何从 Spring MVC 更改/更新以下 REST 调用以返回错误..类似于 NOT FOUND ?

@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;
    }
4

2 回答 2

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();
}
于 2013-06-07T14:19:48.400 回答
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 对象。此对象包含状态代码、状态消息、日期和时间的字段。您可能不需要日期和时间,但我发现当有人向我发送他们看到的错误时它很有用,因为这样很容易在我们的服务器日志中准确追踪它发生的位置。

于 2014-01-08T22:09:27.460 回答