javascript
rest spring_Spring REST:异常处理卷。 2
rest spring
這是有關(guān)使用Spring進(jìn)行REST異常處理的系列的第二篇文章。 在我以前的文章中,我描述了如何在REST服務(wù)中組織最簡(jiǎn)單的異常處理。 這次,我將更進(jìn)一步,并向您展示何時(shí)最好在@ControllerAdvice級(jí)別上使用異常處理 。
介紹
在開始本文的技術(shù)部分之前,我需要考慮一種情況,那就是我們最好在@ControllerAdvice級(jí)別上使用異常處理。
通常,一個(gè)控制器負(fù)責(zé)與一種類型的實(shí)體相關(guān)的整個(gè)邏輯。 這就是說,如果我有一些EntityController類,它將包含該實(shí)體的所有CRUD(創(chuàng)建,讀取,更新,刪除)操作,并且如果需要的話可能包含一些額外的邏輯。 讓我們檢查三個(gè)操作:讀取,更新,刪除。
讀取操作會(huì)根據(jù)我們作為參數(shù)傳遞給它的ID返回一些特定的實(shí)體。 如果實(shí)體不存在,則讀取操作將返回null。 更新/刪除操作分別更新/刪除特定實(shí)體。 這兩個(gè)操作中的每一個(gè)都包含讀取操作,因?yàn)樵诟?刪除實(shí)體之前,我們需要確保它存在于系統(tǒng)中。
在更新/刪除操作過程中未找到實(shí)體時(shí),應(yīng)用程序?qū)伋鯡ntityNotFoundException異常。 在這種情況下,異常處理將非常簡(jiǎn)單。 該應(yīng)用程序必須將信息返回給客戶端:
- 響應(yīng)標(biāo)題:404
- 導(dǎo)致異常的鏈接
- 錯(cuò)誤消息:沒有ID為N的實(shí)體
對(duì)于此類異常,這是最簡(jiǎn)單的響應(yīng)結(jié)構(gòu)。 因此,無論您在應(yīng)用程序中擁有多少個(gè)不同的實(shí)體類,因?yàn)槟伎梢杂孟嗤姆绞教幚眍愃祁愋偷漠惓?#xff08;例如,沒有此類實(shí)體)。 @ControllerAdvice批注使這成為可能。
@ControllerAdvice級(jí)別的異常處理
本文的實(shí)際部分將基于上一教程的申請(qǐng)表。
首先,我需要在message.properties文件中添加一條錯(cuò)誤消息:
error.no.smartphone.id = There is no Smartphone with id:在此之后,讓我們看一下本文主題中對(duì)我們來說有趣的控制器方法。
...@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的調(diào)用。 而且SmartphoneService的實(shí)現(xiàn)包含可以拋出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對(duì)象。 您可以在上一則有關(guān)@Controller級(jí)別的異常處理的文章中了解有關(guān)它的更多信息。
這樣,我們只需將額外的異常類添加到@ExceptionHandler批注中,就可以在一個(gè)地方收集所有類似的異常。 這種方法使整個(gè)應(yīng)用程序中的代碼維護(hù)更加容易。
示例說明:
注意:我以id值= 356發(fā)出了請(qǐng)求,但是數(shù)據(jù)庫中沒有任何記錄與此ID值相對(duì)應(yīng)。 這種情況導(dǎo)致異常。
翻譯自: https://www.javacodegeeks.com/2013/11/spring-rest-exception-handling-vol-2.html
rest spring
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的rest spring_Spring REST:异常处理卷。 2的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Gradle多项目构建–类似父pom的结
- 下一篇: rest spring_Spring R