Spring REST 异常解决
发布时间:2021-11-19 13:49:40 所属栏目:教程 来源:互联网
导读:通过ResponseEntity 通过ResponseEntity接收两个参数,一个是对象,一个是HttpStatus. 举例: @RequestMapping(value=/customer/{id} ) public ResponseEntityCustomer getCustomerById(@PathVariable String id) { Customer customer; try { customer = cus
通过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}" ) @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注解的类中定义从而使异常处理对整个程序有效。 (编辑:东莞站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |