在上一篇中写到了Spring MVC的异常处理,SpringMVC捕获到异常之后会转到相应的错误页面,但是我们REST API ,一般只返回结果和状态码,比如发生异常,只向客户端返回一个500的状态码,和一个错误消息。如果我们不做处理,客户端通过REST API访问,发生异常的话,会得到一个错误页面的html代码。。。这时候怎么做呢, 我现在所知道的就两种做法
通过ResponseEntity接收两个参数,一个是对象,一个是HttpStatus.
举例:
@RequestMapping(value="/customer/{id}" )
public ResponseEntity<Customer> getCustomerById(@PathVariable String id)
{
Customer customer;
try
{
customer = customerService.getCustomerDetail(id);
}
catch (CustomerNotFoundException e)
{
return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Customer>(customer,HttpStatus.OK);
}
这种方法的话我们得在每个RequestMapping 方法中加入try catch语句块,比较麻烦,下面介绍个更简单点的方法
这里跟前面不同的是,我们注解方法的返回值不是一个ResponseEntity对象,而不是跳转的页面。
@RequestMapping(value="/customer/{id}" )
@ResponseBody
public Customer getCustomerById(@PathVariable String id) throws CustomerNotFoundException
{
return customerService.getCustomerDetail(id);
}
@ExceptionHandler(CustomerNotFoundException.class)
public ResponseEntity<ClientErrorInformation> rulesForCustomerNotFound(HttpServletRequest req, Exception e)
{
ClientErrorInformation error = new ClientErrorInformation(e.toString(), req.getRequestURI());
return new ResponseEntity<ClientErrorInformation>(error, HttpStatus.NOT_FOUND);
}
总结:
这里两种方法,推荐使用第二种,我们既可以在单个Controller中定义,也可以在标有ControllerAdvice注解的类中定义从而使异常处理对整个程序有效。
转至:http://www.cnblogs.com/hupengcool/p/4587220.html
?
广告见谅:
获取【下载地址】? ?QQ: 313596790
A 代码生成器(开发利器);??
? ?增删改查的处理类,service层,mybatis的xml,SQL( mysql? ?和oracle)脚本,? ?jsp页面 都生成
? ?就不用写搬砖的代码了,生成的放到项目里,可以直接运行
B 阿里巴巴数据库连接池druid;
??数据库连接池??阿里巴巴的 druid。Druid在监控、可扩展性、稳定性和性能方面都有明显的优势
C 安全权限框架shiro ;
??Shiro 是一个用 Java 语言实现的框架,通过一个简单易用的 API 提供身份验证和授权,更安全,更可靠
D ehcache 自定义二级缓存;
??是一个纯Java的进程内缓存框架,具有快速、精干等特点
??是一种广泛使用的开源Java分布式缓存。
E 微信接口开发(2.5版本新增)(后续会加入Activiti5 工作流 )
原文:http://adminfy.iteye.com/blog/2220972