javascript
rest spring_Spring REST:异常处理卷。 2
rest spring
這是有關使用Spring進行REST異常處理的系列的第二篇文章。 在我以前的文章中,我描述了如何在REST服務中組織最簡單的異常處理。 這次,我將更進一步,并向您展示何時最好在@ControllerAdvice級別上使用異常處理 。
介紹
 在開始本文的技術部分之前,我需要考慮一種情況,那就是我們最好在@ControllerAdvice級別上使用異常處理。 
 通常,一個控制器負責與一種類型的實體相關的整個邏輯。 這就是說,如果我有一些EntityController類,它將包含該實體的所有CRUD(創建,讀取,更新,刪除)操作,并且如果需要的話可能包含一些額外的邏輯。 讓我們檢查三個操作:讀取,更新,刪除。 
讀取操作會根據我們作為參數傳遞給它的ID返回一些特定的實體。 如果實體不存在,則讀取操作將返回null。 更新/刪除操作分別更新/刪除特定實體。 這兩個操作中的每一個都包含讀取操作,因為在更新/刪除實體之前,我們需要確保它存在于系統中。
在更新/刪除操作過程中未找到實體時,應用程序將拋出EntityNotFoundException異常。 在這種情況下,異常處理將非常簡單。 該應用程序必須將信息返回給客戶端:
- 響應標題:404
- 導致異常的鏈接
- 錯誤消息:沒有ID為N的實體
對于此類異常,這是最簡單的響應結構。 因此,無論您在應用程序中擁有多少個不同的實體類,因為您都可以用相同的方式處理類似類型的異常(例如,沒有此類實體)。 @ControllerAdvice批注使這成為可能。
@ControllerAdvice級別的異常處理
本文的實際部分將基于上一教程的申請表。
首先,我需要在message.properties文件中添加一條錯誤消息:
error.no.smartphone.id = There is no Smartphone with id:在此之后,讓我們看一下本文主題中對我們來說有趣的控制器方法。
...@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)public ModelAndView editSmartphonePage(@PathVariable int id) {ModelAndView mav = new ModelAndView("phones/edit-phone");Smartphone smartphone = smartphoneService.get(id);mav.addObject("sPhone", smartphone);return mav;}@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic Smartphone editSmartphone(@PathVariable int id, @Valid @RequestBody Smartphone smartphone) {smartphone.setId(id);return smartphoneService.update(smartphone);} ...@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic Smartphone deleteSmartphone(@PathVariable int id) {return smartphoneService.delete(id);} ...這些方法包括SmartphoneService的調用。 而且SmartphoneService的實現包含可以拋出SmartphoneNotFoundException的方法 。
@Service @Transactional(rollbackFor = { SmartphoneNotFoundException.class }) public class SmartphoneServiceImpl implements SmartphoneService {@Autowiredprivate SmartphoneRepository smartphoneRepository;@Overridepublic Smartphone create(Smartphone sp) {return smartphoneRepository.save(sp);}@Overridepublic Smartphone get(Integer id) {Smartphone sp = null;if (id instanceof Integer)sp = smartphoneRepository.findOne(id);if (sp != null)return sp;throw new SmartphoneNotFoundException(id);}@Overridepublic List getAll() {return smartphoneRepository.findAll();}@Overridepublic Smartphone update(Smartphone sp) {Smartphone sPhoneToUpdate = get(sp.getId());sPhoneToUpdate.update(sp);return sPhoneToUpdate;}@Overridepublic Smartphone delete(Integer id) {Smartphone sPhone = get(id);smartphoneRepository.delete(id);return sPhone;}}這是SmartphoneNotFoundException的代碼:
public class SmartphoneNotFoundException extends RuntimeException {private static final long serialVersionUID = -2859292084648724403L;private final int smartphoneId;public SmartphoneNotFoundException(int id) {smartphoneId = id;}public int getSmartphoneId() {return smartphoneId;}}最后,我可以移至@ControllerAdvice 。
@ControllerAdvice public class RestExceptionProcessor {@Autowiredprivate MessageSource messageSource;@ExceptionHandler(SmartphoneNotFoundException.class)@ResponseStatus(value=HttpStatus.NOT_FOUND)@ResponseBodypublic ErrorInfo smartphoneNotFound(HttpServletRequest req, SmartphoneNotFoundException ex) {Locale locale = LocaleContextHolder.getLocale();String errorMessage = messageSource.getMessage("error.no.smartphone.id", null, locale);errorMessage += ex.getSmartphoneId();String errorURL = req.getRequestURL().toString();return new ErrorInfo(errorURL, errorMessage);}}異常處理程序方法返回ErrorInfo對象。 您可以在上一則有關@Controller級別的異常處理的文章中了解有關它的更多信息。
這樣,我們只需將額外的異常類添加到@ExceptionHandler批注中,就可以在一個地方收集所有類似的異常。 這種方法使整個應用程序中的代碼維護更加容易。
示例說明:
 注意:我以id值= 356發出了請求,但是數據庫中沒有任何記錄與此ID值相對應。 這種情況導致異常。 
翻譯自: https://www.javacodegeeks.com/2013/11/spring-rest-exception-handling-vol-2.html
rest spring
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的rest spring_Spring REST:异常处理卷。 2的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Gradle多项目构建–类似父pom的结
- 下一篇: 手机qq怎么设置密码锁(手机qq怎么设置
