日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring REST:异常处理卷。 2

發(fā)布時間:2023/12/3 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring REST:异常处理卷。 2 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

這是有關使用Spring進行REST異常處理的系列的第二篇文章。 在我以前的文章中,我描述了如何在REST服務中組織最簡單的異常處理。 這次,我將更進一步,我將向您展示何時最好在@ControllerAdvice級別使用異常處理 。

介紹

在開始本文的技術部分之前,我需要考慮一種情況,那就是我們最好在@ControllerAdvice級別上使用異常處理。
通常,一個控制器負責與一種類型的實體相關的整個邏輯。 就是說,如果我有一些EntityController類,它將包含與實體有關的所有CRUD(創(chuàng)建,讀取,更新,刪除)操作,如果需要的話,還可能包含一些額外的邏輯。 讓我們檢查三個操作:讀取,更新,刪除。

讀取操作會根據(jù)ID(我們將其作為參數(shù)傳遞給它)返回一些特定的實體。 如果實體不存在,則讀取操作將返回null。 更新/刪除操作分別更新/刪除特定實體。 這兩個操作中的每一個都包含讀取操作,因為在更新/刪除實體之前,我們需要確保其存在于系統(tǒng)中。

在更新/刪除操作過程中未找到實體時,應用程序將拋出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的實現(xiàn)包含可以引發(fā)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批注中,就可以在一個地方收集所有類似的異常。 這種方法使整個應用程序內的代碼維護更加容易。

示例說明:

注意:我發(fā)出了id值為356的請求,但是數(shù)據(jù)庫中沒有任何記錄與此ID值相對應。 這種情況導致異常。

參考: Spring REST:異常處理卷。 2來自我們的JCG合作伙伴 Alexey Zvolinskiy,在Fruzenshtein的筆記博客中。

翻譯自: https://www.javacodegeeks.com/2013/11/spring-rest-exception-handling-vol-2.html

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結

以上是生活随笔為你收集整理的Spring REST:异常处理卷。 2的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。