@RestControllerAdvice注解使用


在spring 3.2中,新增了@ControllerAdvice,@RestControllerAdvice 注解,可以用於定義@ExceptionHandler、@InitBinder、@ModelAttribute,並應用到所有@RequestMapping中。參考幫助文檔@RestControllerAdvice 是組件注解,他使得其實現類能夠被classpath掃描自動發現,如果應用是通過MVC命令空間或MVC Java編程方式配置,那么該特性默認是自動開啟的

  主要配合@ExceptionHandler使用,統一處理異常情況。下面的ResponseEntity、ResponseData 都是項目自定義的返回對象。

 

 

package com.cpic.chjb.web.framework.web.handler;


import com.cpic.chjb.common.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import com.cpic.chjb.common.exception.CommonException;

@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

@ExceptionHandler(RuntimeException.class)
public Result handlerException(RuntimeException re) {
log.info(re.getMessage(),re);
Result result = new Result();
result.setCode(500);
result.setMsg("系統運行時異常,請聯系管理員!");
return result;
}

@ExceptionHandler(MaxUploadSizeExceededException.class)
public Result handlerException(MaxUploadSizeExceededException e){
log.info(e.getMessage(),e);
Result result = new Result();
result.setCode(500);
result.setMsg("文件大小超出5MB限制, 請壓縮或降低文件質量!");
return result;
}

@ExceptionHandler(CommonException.class)
public Result handlerException(CommonException ce) {
log.info(ce.getMessage(),ce);
Result result = new Result();
result.setCode(ce.getCode());
result.setMsg(ce.getMessage());
return result;
}

@ExceptionHandler(Exception.class)
public Result handlerException(Exception e) {
log.info(e.getMessage(),e);
Result result = new Result();
result.setCode(500);
result.setMsg( "系統異常");
return result;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM