java異常統一處理
阿新 • • 發佈:2018-09-12
出現 actor 錯誤 統一處理 type .get 。。 cfa getc
一般系統拋出的錯誤不含錯誤代碼,出去部分的404,500,400之外,我們如果想吧錯誤代碼定義的更細致,就需要自己繼承RuntimeExeption這個類後,重新定義構造方法定義自己的錯誤信息。
public class DescribeException extends RuntimeException{ private Integer code; /** * 繼承exception,加入錯誤狀態值 * @param exceptionEnum */ public DescribeException(ExceptionEnum exceptionEnum) { super(exceptionEnum.getMsg()); this.code = exceptionEnum.getCode(); } /** * 自定義錯誤信息 * @param message * @param code */ public DescribeException(String message, Integer code) { super(message); this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }View Code
使用一個handler來判定我們try。。。catch。。。的錯誤是我們已知的錯誤還是未知的,如果已知,返回錯誤,未知返回未知錯誤和記錄日誌,留著以後查找錯誤。
@ControllerAdvice public class ExceptionHandle { private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class); /** * 判斷錯誤是否是已定義的已知錯誤,不是則由未知錯誤代替,同時記錄在log中 * @param e * @return */ @ExceptionHandler(value = Exception.class) @ResponseBody public Result exceptionGet(Exception e){ if(e instanceof DescribeException){ DescribeException MyException = (DescribeException) e; return ResultUtil.error(MyException.getCode(),MyException.getMessage()); } LOGGER.error("【系統異常】{}",e); return ResultUtil.error(ExceptionEnum.UNKNOW_ERROR); } }View Code
這樣我們就不用返回日誌到前端了,讓用戶感覺很奇怪。
但是這時候調用接口出現異常,我們怎麽來判斷是前端還是後端造成的問題呢。這時候就要用aop進行攔截
@Aspect @Component public class HttpAspect { private final static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class); @Autowired private ExceptionHandle exceptionHandle; @Pointcut("execution(public * com.zzp.controller.*.*(..))") public void log(){ } @Before("log()") public void doBefore(JoinPoint joinPoint){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //url LOGGER.info("url={}",request.getRequestURL()); //method LOGGER.info("method={}",request.getMethod()); //ip LOGGER.info("id={}",request.getRemoteAddr()); //class_method LOGGER.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName()); //args[] LOGGER.info("args={}",joinPoint.getArgs()); } @Around("log()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Result result = null; try { } catch (Exception e) { return exceptionHandle.exceptionGet(e); } if(result == null){ return proceedingJoinPoint.proceed(); }else { return result; } } @AfterReturning(pointcut = "log()",returning = "object")//打印輸出結果 public void doAfterReturing(Object object){ LOGGER.info("response={}",object.toString()); } }View Code
java異常統一處理