




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第詳解java封裝返回結(jié)果與RestControllerAdvice注解目錄1.為什么要把結(jié)果封裝成統(tǒng)一格式?2.統(tǒng)一異常接收
1.為什么要把結(jié)果封裝成統(tǒng)一格式?
異常和正常情況無法區(qū)分:異常情況返回?cái)?shù)據(jù)為null,正常情況下查詢結(jié)果也為null,返回給前端無法區(qū)分
顯示拋出異常信息:前端需要顯示拋出的異常信息
@AllArgsConstructor
publicenumResultCode{
CODE_200(200,"success"),
CODE_1000(1000,"fail");
@Getter
privateIntegercode;
@Getter
privateStringmsg;
@Data
publicclassResultT{
privateStringmsg;
privateIntegercode;
privateTdata;
privateResult(Stringmsg,Integercode){
this.msg=msg;
this.code=code;
privateResult(ResultCoderesultCode,Stringmsg){
this(msg,resultCode.getCode());
privateResult(ResultCoderesultCode){
this(resultCode.getMsg(),resultCode.getCode());
publicstaticTResultTresult(ResultCoderesultCode,Tdata){
Resultresult=newResult(resultCode);
result.setData(data);
returnresult;
publicstaticTResultTfail(ResultCoderesultCode,Stringmessage){
Resultresult=newResult(resultCode,message);
result.setData(null);
returnresult;
publicstaticTResultTfail(Tdata){
Resultresult=newResult(ResultCode.CODE_1000);
result.setData(data);
returnresult;
publicstaticTResultTsuccess(Tdata){
Resultresult=newResult(ResultCode.CODE_200);
result.setData(data);
returnresult;
不封裝:
封裝:
2.統(tǒng)一異常接收
為什么要用統(tǒng)一異常接收?
通常在service層拋異常,涉及到事務(wù)時(shí)不會(huì)進(jìn)行try-catch,需要在controller里處理異常。即使能夠進(jìn)行try-catch的地方也需要統(tǒng)一返回格式,造成重復(fù)代碼很多,可讀性比較差。
如何實(shí)現(xiàn)統(tǒng)一的異常接收?
@Slf4j
@RestControllerAdvice
publicclassGlobalException{
@ExceptionHandler(Exception.class)
publicResulthandlerException(Exceptionexception){
("Exception異常信息:"+exception.getMessage());
returnResult.fail(ResultCode.CODE_1000,exception.getMessage());
@ExceptionHandler(value={MyException.class})
publicResulthandlerMyException(Exceptionexception){
("MyException異常信息:"+exception.getMessage());
returnResult.fail(ResultCode.CODE_1000,exception.getMessage());
拋出異常后,會(huì)進(jìn)入到@RestControllerAdvice注解的方法,過濾出和拋出異常相同的class的方法,執(zhí)行相應(yīng)的方法。
protectedModelAndViewdoResolveHandlerMethodException(HttpServletRequestrequest,HttpServletResponseresponse,@NullableHandlerMethodhandlerMethod,Exceptionexception){
//根據(jù)異常類型過濾方法
ServletInvocableHandlerMethodexceptionHandlerMethod=this.getExceptionHandlerMethod(handlerMethod,exception);
if(exceptionHandlerMethod==null){
returnnull;
}else{
if(this.argumentResolvers!=null){
exceptionHandlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
if(this.returnValueHandlers!=null){
exceptionHandlerMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
ServletWebRequestwebRequest=newServletWebRequest(request,response);
ModelAndViewContainermavContainer=newModelAndViewContainer();
ArrayListThrowableexceptions=newArrayList();
try{
if(this.logger.isDebugEnabled()){
this.logger.debug("Using@ExceptionHandler"+exceptionHandlerMethod);
Throwablecause;
for(ThrowableexToExpose=exception;exToExpose!=null;exToExpose=cause!=exToExposecause:null){
exceptions.add(exToExpose);
cause=((Throwable)exToExpose).getCause();
Object[]arguments=newObject[exceptions.size()+1];
exceptions.toArray(arguments);
arguments[arguments.length-1]=handlerMethod;
//執(zhí)行方法
exceptionHandlerMethod.invokeAndHandle(webRequest,mavContainer,arguments);
}catch(Throwablevar13){
if(!exceptions.contains(var13)this.logger.isWarnEnabled()){
this.logger.warn("Failurein@ExceptionHandler"+exceptionHandlerMethod,var13);
returnnull;
if(mavContainer.isRequestHandled()){
returnnewModelAndView();
}else{
ModelMapmodel=mavContainer.getModel();
HttpStatusstatus=mavContainer.getStatus();
ModelAndViewmav=newModelAndView(mavContainer.getViewName(),model,status);
mav.setViewName(mavContainer.getViewName());
if(!mavContainer.isViewReference()){
mav.setView((View)mavContainer.getView());
if(modelinstanceofRedirectAttributes){
MapString,flashAttributes=((RedirectAttributes)model).getFlashAttributes();
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
returnmav;
protectedServletInvocableHandlerMethodgetExceptionHandlerMethod(@NullableHandlerMethodhandlerMethod,Exceptionexception){
ClasshandlerType=null;
if(handlerMethod!=null){
handlerType=handlerMethod.getBeanType();
ExceptionHandlerMethodResolverresolver=(ExceptionHandlerMethodResolver)this.exceptionHandlerCache.get(handlerType);
if(resolver==null){
resolver=newExceptionHandlerMethodResolver(handlerType);
this.exceptionHandlerCache.put(handlerType,resolver);
Methodmethod=resolver.resolveMethod(exception);
if(method!=null){
returnnewServletInvocableHandlerMethod(handlerMethod.getBean(),method,this.applicationContext);
if(Proxy.isProxyClass(handlerType)){
handlerType=AopUtils.getTargetClass(handlerMethod.getBean());
//初始化的時(shí)候已經(jīng)將beanType作為key,標(biāo)注@ExceptionHandler的方法包裝成resolve作為value放到exceptionHandlerAdviceCache中
Iteratorvar9=this.exceptionHandlerAdviceCache.entrySet().iterator();
while(var9.hasNext()){
Map.EntryControllerAdviceBean,ExceptionHandlerMethodResolverentry=(Map.Entry)var9.next();
ControllerAdviceBeanadvice=(ControllerAdviceBean)entry.getKey();
if(advice.isApplicableToBeanType(handlerType)){
ExceptionHandlerMethodResolverresolver=(ExceptionHandlerMethodResolver)entry
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 油脂加工機(jī)械液壓系統(tǒng)批發(fā)考核試卷
- 生產(chǎn)過程節(jié)能改造項(xiàng)目評(píng)估考核試卷
- 太平金科面試題及答案
- 車間統(tǒng)計(jì)考試題及答案
- 信用服務(wù)在汽車金融租賃市場(chǎng)的創(chuàng)新應(yīng)用考核試卷
- 電路方面試題及答案
- 宣教信息面試題及答案
- 藥師人衛(wèi)資格考試試題及答案
- 房地產(chǎn)采購(gòu)合同模板
- 構(gòu)建校園安全教育主題體驗(yàn)方案強(qiáng)
- 2025年吉林省中考數(shù)學(xué)試卷真題及答案詳解(精校打印版)
- 2024年惠州市第一婦幼保健院招聘衛(wèi)生專業(yè)技術(shù)人員考試真題
- 譯林版(2024)七年級(jí)下冊(cè)英語期末復(fù)習(xí)綜合練習(xí)試卷(含答案)
- 2025年園藝師職業(yè)資格考試卷及答案
- 放射職業(yè)衛(wèi)生培訓(xùn)課件
- 2024年天津高中學(xué)業(yè)水平合格性考試歷史試卷真題(含答案詳解)
- GB/T 5163-2006燒結(jié)金屬材料(不包括硬質(zhì)合金)可滲性燒結(jié)金屬材料密度、含油率和開孔率的測(cè)定
- 信陽市平橋區(qū)農(nóng)村土地承包經(jīng)營(yíng)權(quán)轉(zhuǎn)包
- 《城市軌道交通通風(fēng)與空調(diào)系統(tǒng)》教學(xué)課件—07地鐵通風(fēng)空調(diào)概述
- 化學(xué)常用單詞匯總
- 西子otis梯oh con6423中文調(diào)試手冊(cè)
評(píng)論
0/150
提交評(píng)論