本文介绍了如何将错误添加到Spring MVC REST服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未输入我正在编码的两个名称,那么如何更改/更新来自Spring MVC的以下REST调用以返回错误.

How can I change/update the following REST call from Spring MVC to return a error if the user did not enter of the the two names I was coding for.. something like a 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;
    }

推荐答案

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

Define a new exception class, e.g. ResourceNotFoundException and throw an instance of this from your annotated controller method getName.

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

Then also define an annotated exception handler method in your Controller class to handle that exception, and return a 404 Not Found status code, potentially logging it.

@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批注返回一些错误消息:

Or even returning some error message, using @ResponseBody annotation:

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

这篇关于如何将错误添加到Spring MVC REST服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 19:34