在上一篇中写到了Spring MVC的异常处理,SpringMVC捕获到异常以后会转到相应的错误页面,可是咱们REST API ,通常只返回结果和状态码,好比发生异常,只向客户端返回一个500的状态码,和一个错误消息。若是咱们不作处理,客户端经过REST API访问,发生异常的话,会获得一个错误页面的html代码。。。这时候怎么作呢, 我如今所知道的就两种作法html
经过ResponseEntity接收两个参数,一个是对象,一个是HttpStatus.
举例:java
@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语句块,比较麻烦,下面介绍个更简单点的方法app
这里跟前面不一样的是,咱们注解方法的返回值不是一个ResponseEntity对象,而不是跳转的页面。code
@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注解的类中定义从而使异常处理对整个程序有效。orm