1

Spring MVC REST 服务和客户端。我正在寻找一种更好的方法来处理错误!

我有时想向客户端返回错误消息或状态代码,但我不知道如何。有人可以告诉我如何找到更好的方法来处理 Spring REST 服务和客户端的错误和错误消息。

这是我的服务代码:

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

    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 ("user2".equals(name))
    {
        return new User("User2 Real Name", name);
    }

    if ("user1".equals(name))
    {
        return new User("User1 Real Name", name);
    }

    throw new ResourceNotFoundException("User Is Not Found");
}


 @ExceptionHandler(ResourceNotFoundException.class)
 public ModelAndView handleResourceNotFoundException(ResourceNotFoundException ex)
{
    logger.warn("user requested a resource which didn't exist", ex);
    return new ModelAndView( jsonView, "error", "user requested a resource which didn't exist");
}

现在这里是客户端的代码:

Map<String, String> vars = new HashMap<String, String>();
vars.put("name", "user1");


/**
 *
 * Doing the REST call and then displaying the data/user object
 *
 */
RestTemplate restTemplate = new RestTemplate(commons);
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

try
{
    User jsonreturn = restTemplate.getForObject("http://" + mRESTServer.getHost() + ":8080/json/{name}", User.class, vars);
    LOGGER.debug("return object:  " + jsonreturn.toString());
}
catch(Exception e)
{
    LOGGER.error("error:  " + e.toString());
}

如果找不到用户并且我的客户端代码收到此错误,我想找到返回状态代码和消息的方法:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "error"
4

2 回答 2

2

我已经使用这种方法(使用 JSON/Jackson 2)取得了良好的成功:

class ErrorHolder {
    public String errorMessage;
    public ErrorHolder(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

@ExceptionHandler
public @ResponseBody ResponseEntity<ErrorHolder> handle(ResourceNotFoundException e) {
    logger.warn("Teh resource was not found", e);
    return new ResponseEntity<ErrorHolder>(new ErrorHolder("Uh oh"), HttpStatus.NOT_FOUND);
}

至少适用于 Spring 3.2.x。

于 2013-06-07T21:09:57.690 回答
0

我认为重点是如何处理正确的返回对象和错误的对象。在您的客户中:

try
{
    User jsonreturn = restTemplate.getForObject("http://" + mRESTServer.getHost() + ":8080/json/{name}", User.class, vars);
    LOGGER.debug("return object:  " + jsonreturn.toString());
}
catch(Exception e)
{
    LOGGER.error("error:  " + e.toString());
}

发生错误时,返回对象不是User,所以messageConverter不能正常工作。</p>

我的解决方案是:在服务器端,使用response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 那么客户端就不会使用 messageConverter 了,比如 throw HttpClientErrorException 或者 HttpServerErrorException ,都有响应体,所以你可以调用他们的 e.getResponseBodyAsString() 来获取错误信息。

于 2013-12-02T06:09:22.033 回答