首页 / 操作系统 / Linux / Spring REST 异常处理
在上一篇中写到了Spring MVC的异常处理【见 http://www.linuxidc.com/Linux/2015-06/119049.htm】,SpringMVC捕获到异常之后会转到相应的错误页面,但是我们REST API ,一般只返回结果和状态码,比如发生异常,只向客户端返回一个500的状态码,和一个错误消息。如果我们不做处理,客户端通过REST API访问,发生异常的话,会得到一个错误页面的html代码。。。这时候怎么做呢, 我现在所知道的就两种做法
通过ResponseEntity
通过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语句块,比较麻烦,下面介绍个更简单点的方法通过ExceptionHandler注解
这里跟前面不同的是,我们注解方法的返回值不是一个ResponseEntity对象,而不是跳转的页面。@RequestMapping(value="/customer/{id}" )@ResponseBodypublic 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注解的类中定义从而使异常处理对整个程序有效。--------------------------------------分割线 --------------------------------------Spring中如何配置Hibernate事务 http://www.linuxidc.com/Linux/2013-12/93681.htmStruts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm基于 Spring 设计并实现 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htmSpring-3.2.4 + Quartz-2.2.0集成实例 http://www.linuxidc.com/Linux/2013-10/91524.htm使用 Spring 进行单元测试 http://www.linuxidc.com/Linux/2013-09/89913.htm运用Spring注解实现Netty服务器端UDP应用程序 http://www.linuxidc.com/Linux/2013-09/89780.htmSpring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码 http://www.linuxidc.com/Linux/2013-10/91357.htm--------------------------------------分割线 --------------------------------------Spring 的详细介绍:请点这里
Spring 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-06/119050.htm