BaseResponse是返回给前端的封装对象,捕获到后返回给前端异常信息
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.yss.base.msg.BaseResponse;
import com.yss.base.msg.expection.BadRequestException;
import com.yss.base.msg.expection.EntityExistException;
import com.yss.base.msg.expection.EntityNotFoundException;
import com.yss.base.utils.ThrowableUtil;
import static org.springframework.http.HttpStatus.*;
/**
* @author inspur
* @date 2020-04-20
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log=LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理所有不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public BaseResponse handleException(Exception e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return new BaseResponse(BAD_REQUEST.value(),e.getMessage());
}
/**
* 处理 接口无权访问异常AccessDeniedException
* @param e
* @return
*/
@ExceptionHandler(AccessDeniedException.class)
public BaseResponse handleAccessDeniedException(AccessDeniedException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return new BaseResponse(FORBIDDEN.value(),e.getMessage());
}
/**
* 处理自定义异常
* @param e
* @return
*/
@ExceptionHandler(value = BadRequestException.class)
public BaseResponse badRequestException(BadRequestException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return new BaseResponse(e.getStatus(),e.getMessage());
}
/**
* 处理 EntityExist
* @param e
* @return
*/
@ExceptionHandler(value = EntityExistException.class)
public BaseResponse entityExistException(EntityExistException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return new BaseResponse(BAD_REQUEST.value(),e.getMessage());
}
/**
* 处理 EntityNotFound
* @param e
* @return
*/
@ExceptionHandler(value = EntityNotFoundException.class)
public BaseResponse entityNotFoundException(EntityNotFoundException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return new BaseResponse(NOT_FOUND.value(),e.getMessage());
}
/**
* 处理所有接口数据验证异常
* @param e
* @returns
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public BaseResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
String[] str = e.getBindingResult().getAllErrors().get(0).getCodes()[1].split("\\.");
StringBuffer msg = new StringBuffer(str[1]+":");
msg.append(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return new BaseResponse(BAD_REQUEST.value(),msg.toString());
}
}