♻️ 重构代码,异常处理交给exceptionhandler

This commit is contained in:
冷冷 2018-05-24 16:08:34 +08:00
parent 7ceb7d4845
commit fd117d96ec
2 changed files with 47 additions and 14 deletions

View File

@ -36,7 +36,7 @@ public class ControllerAop {
* @return R 结果包装
*/
@Around("pointCutR()")
public Object methodRHandler(ProceedingJoinPoint pjp) {
public Object methodRHandler(ProceedingJoinPoint pjp) throws Throwable {
return methodHandler(pjp);
}
@ -52,18 +52,18 @@ public class ControllerAop {
* @return R 结果包装
*/
@Around("pointCutPage()")
public Object methodPageHandler(ProceedingJoinPoint pjp) {
public Object methodPageHandler(ProceedingJoinPoint pjp) throws Throwable {
return methodHandler(pjp);
}
private Object methodHandler(ProceedingJoinPoint pjp) {
private Object methodHandler(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String username = request.getHeader(SecurityConstants.USER_HEADER);
if (StrUtil.isNotBlank(username)){
if (StrUtil.isNotBlank(username)) {
log.info("Controller AOP get username:{}", username);
UserUtils.setUser(username);
}
@ -76,16 +76,11 @@ public class ControllerAop {
Object result;
try {
result = pjp.proceed();
log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
} catch (Throwable e) {
log.error("异常信息:", e);
throw new RuntimeException(e);
} finally {
if (StrUtil.isNotEmpty(username)) {
UserUtils.clearAllUserInfo();
}
result = pjp.proceed();
log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
if (StrUtil.isNotEmpty(username)) {
UserUtils.clearAllUserInfo();
}
return result;

View File

@ -0,0 +1,38 @@
package com.github.pig.common.bean.handler;
/**
* @author lengleng
* @date 2018/5/24
*/
import com.github.pig.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局的的异常拦截器
*
* @author lengleng
* @date 2018/05/22
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常.
*
* @param e the e
* @return R
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public R exception(Exception e) {
log.info("保存全局异常信息 ex={}", e.getMessage(), e);
return new R<>(e);
}
}