如果用户没有输入我正在编码的两个名称,我如何更改/更新来自 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 two 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
.
然后还在您的 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)