♻️ 重构代码,异常处理交给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 结果包装 * @return R 结果包装
*/ */
@Around("pointCutR()") @Around("pointCutR()")
public Object methodRHandler(ProceedingJoinPoint pjp) { public Object methodRHandler(ProceedingJoinPoint pjp) throws Throwable {
return methodHandler(pjp); return methodHandler(pjp);
} }
@ -52,11 +52,11 @@ public class ControllerAop {
* @return R 结果包装 * @return R 结果包装
*/ */
@Around("pointCutPage()") @Around("pointCutPage()")
public Object methodPageHandler(ProceedingJoinPoint pjp) { public Object methodPageHandler(ProceedingJoinPoint pjp) throws Throwable {
return methodHandler(pjp); return methodHandler(pjp);
} }
private Object methodHandler(ProceedingJoinPoint pjp) { private Object methodHandler(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
@ -76,17 +76,12 @@ public class ControllerAop {
Object result; Object result;
try {
result = pjp.proceed(); result = pjp.proceed();
log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime)); log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
} catch (Throwable e) {
log.error("异常信息:", e);
throw new RuntimeException(e);
} finally {
if (StrUtil.isNotEmpty(username)) { if (StrUtil.isNotEmpty(username)) {
UserUtils.clearAllUserInfo(); UserUtils.clearAllUserInfo();
} }
}
return result; 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);
}
}