ControllerAdvice 文檔
在spring 3.2中,新增了@ControllerAdvice 注解,它通常用于定義@ExceptionHandler, @InitBinder和@ModelAttribute 适用于所有@RequestMapping方法的方法。 此文檔主要講解如何全局捕獲異常并傳回給前端
package com.dolphin.sigle.root.config.eorr;
import com.dolphin.common.response.CommonResult;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 開發公司:青島海豚資料技術有限公司
* 版權:青島海豚資料技術有限公司
* <p>
* ExceptionHandler
*
* @author 劉志強
* @created Create Time: 2019/1/19
*/
@RestController
@ControllerAdvice
@CrossOrigin
public class AdviceController {
/**
* validation參數校驗異常
*
* @param ex
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public CommonResult<String> handlerUserNotExistException(MethodArgumentNotValidException ex) {
CommonResult<String> commonResult = new CommonResult<String>();
commonResult.setCode(5100);
String eorrs = "|";
List<FieldError> eorrList = ex.getBindingResult().getFieldErrors();
for (FieldError fieldError : eorrList) {
eorrs = eorrs + fieldError.getDefaultMessage() + "|";
}
commonResult.setMessage(eorrs);
commonResult.setMsg(eorrs);
return commonResult;
}
/**
* shiro權限異常
* @param ex
* @return
*/
@ExceptionHandler(AuthorizationException.class)
public CommonResult<String> authorizationException(AuthorizationException ex) {
CommonResult<String> commonResult = new CommonResult<String>();
if (ex instanceof UnauthenticatedException) {
commonResult.setCode(120);
commonResult.setMessage("token錯誤");
commonResult.setMsg("token錯誤");
} else if (ex instanceof UnauthorizedException) {
commonResult.setCode(5202);
commonResult.setMessage("使用者無權限");
commonResult.setMsg("使用者無權限");
} else {
commonResult.setCode(5203);
commonResult.setMsg(ex.getMessage());
}
return commonResult;
}
.
.
.
.
.
.
}