1.異常攔截類的創建
package com.liqi.web.core.exception; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.liqi.common.base.Constants; import com.liqi.common.base.ResultBean; import com.liqi.common.exception.BusinessInterfaceException; import com.liqi.common.exception.bean.ErrorBean; import lombok.extern.slf4j.Slf4j; /** * 自定義異常處理器 * * @author ieflex */ @RestControllerAdvice @Slf4j public class InterfaceExceptionHandler { /** * 接口 業務異常 */ @ResponseBody @ExceptionHandler(BusinessInterfaceException.class) public String businessInterfaceException(BusinessInterfaceException e) { log.error(e.getMessage(), e); ErrorBean error = e.getError(); ResultBean resultBean = new ResultBean(error.hashCode(), error.getErrorMsg()); return resultBean.toString(); } /** * 攔截所有運行時的全局異常 */ @ExceptionHandler(RuntimeException.class) @ResponseBody public String runtimeException(RuntimeException e) { log.error(e.getMessage(), e); // 返回 JOSN ResultBean resultBean = new ResultBean(Constants.INTERFACE_MSG_301, Constants.INTERFACE_MSG_301_TEXT); return resultBean.toString(); } /** * 系統異常捕獲處理 */ @ExceptionHandler(Exception.class) @ResponseBody public String exception(Exception e) { log.error(e.getMessage(), e); ResultBean resultBean = new ResultBean(Constants.INTERFACE_MSG_301, Constants.INTERFACE_MSG_301_TEXT); // 返回 JOSN return resultBean.toString(); } }
2.controller 測試
package com.springboot_Error.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ErrorControllerTest { //全局異常攔截 測試 @RequestMapping("/ErrorTest") public String index2(){ System.err.println("請求成功!"); int i = 1/0; //這里會有一個運算異常 return "index"; } }
3.啟動 springboot 工程
package com.springboot_Error.ErrorRun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; //掃描 com.springboot_Error.ErrorController 包下 controller 注解過的類 @ComponentScan(basePackages={"com.springboot_Error.ErrorController"}) @EnableAutoConfiguration public class ErrorRun { public static void main(String[] args) { SpringApplication.run(ErrorRun.class, args); } }
4.測試
/** * 功能描述: 模擬自定義異常 * @return */ @RequestMapping(value = "/api/test") public Object myext() { throw new BusinessInterfaceException("500", "my ext異常"); }
經過測試發現可以捕獲到Controller層的異常,當前前提是Controller層沒有對異常進行catch處理,如果Controller層對異常進行了catch處理,那么在這里就不會捕獲到Controller層的異常了,所以這一點要注意。
5.基於Springboot自身的全局異常統一處理
主要是實現ErrorController接口或者繼承AbstractErrorController抽象類或者繼承BasicErrorController類
@Controller @RequestMapping(value = "error") @EnableConfigurationProperties({ServerProperties.class}) public class ExceptionController implements ErrorController { private ErrorAttributes errorAttributes; @Autowired private ServerProperties serverProperties; /** * 初始化ExceptionController * @param errorAttributes */ @Autowired public ExceptionController(ErrorAttributes errorAttributes) { Assert.notNull(errorAttributes, "ErrorAttributes must not be null"); this.errorAttributes = errorAttributes; } /** * 定義404的ModelAndView * @param request * @param response * @return */ @RequestMapping(produces = "text/html",value = "404") public ModelAndView errorHtml404(HttpServletRequest request, HttpServletResponse response) { response.setStatus(getStatus(request).value()); Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); return new ModelAndView("error/404", model); } /** * 定義404的JSON數據 * @param request * @return */ @RequestMapping(value = "404") @ResponseBody public ResponseEntity<Map<String, Object>> error404(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); HttpStatus status = getStatus(request); return new ResponseEntity<Map<String, Object>>(body, status); } /** * 定義500的ModelAndView * @param request * @param response * @return */ @RequestMapping(produces = "text/html",value = "500") public ModelAndView errorHtml500(HttpServletRequest request, HttpServletResponse response) { response.setStatus(getStatus(request).value()); Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); return new ModelAndView("error/500", model); } /** * 定義500的錯誤JSON信息 * @param request * @return */ @RequestMapping(value = "500") @ResponseBody public ResponseEntity<Map<String, Object>> error500(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); HttpStatus status = getStatus(request); return new ResponseEntity<Map<String, Object>>(body, status); } /** * Determine if the stacktrace attribute should be included. * @param request the source request * @param produces the media type produced (or {@code MediaType.ALL}) * @return if the stacktrace attribute should be included */ protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) { ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace(); if (include == ErrorProperties.IncludeStacktrace.ALWAYS) { return true; } if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) { return getTraceParameter(request); } return false; } /** * 獲取錯誤的信息 * @param request * @param includeStackTrace * @return */ private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { RequestAttributes requestAttributes = new ServletRequestAttributes(request); return this.errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); } /** * 是否包含trace * @param request * @return */ private boolean getTraceParameter(HttpServletRequest request) { String parameter = request.getParameter("trace"); if (parameter == null) { return false; } return !"false".equals(parameter.toLowerCase()); } /** * 獲取錯誤編碼 * @param request * @return */ private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request .getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } try { return HttpStatus.valueOf(statusCode); } catch (Exception ex) { return HttpStatus.INTERNAL_SERVER_ERROR; } } /** * 實現錯誤路徑,暫時無用 * @see ExceptionMvcAutoConfiguration#containerCustomizer() * @return */ @Override public String getErrorPath() { return ""; } }
6.AOP也可以實現異常的全局處理
@Component @Aspect public class ExceptionAspectController { public static final Logger logger = LoggerFactory.getLogger(ExceptionAspectController.class); @Pointcut("execution(* com.test.test.*.*(..))")//此處基於自身項目的路徑做具體的設置 public void pointCut(){} @Around("pointCut()") public Object handleControllerMethod(ProceedingJoinPoint pjp) { Stopwatch stopwatch = Stopwatch.createStarted(); APIResponse<?> apiResponse; try { logger.info("執行Controller開始: " + pjp.getSignature() + " 參數:" + Lists.newArrayList(pjp.getArgs()).toString()); apiResponse = (APIResponse<?>) pjp.proceed(pjp.getArgs()); logger.info("執行Controller結束: " + pjp.getSignature() + ", 返回值:" + apiResponse.toString()); logger.info("耗時:" + stopwatch.stop().elapsed(TimeUnit.MILLISECONDS) + "(毫秒)."); } catch (Throwable throwable) { apiResponse = handlerException(pjp, throwable); } return apiResponse; } private APIResponse<?> handlerException(ProceedingJoinPoint pjp, Throwable e) { APIResponse<?> apiResponse = null; if(e.getClass().isAssignableFrom(MessageCenterException.class) ){ MessageCenterException messageCenterException = (MessageCenterException)e; logger.error("RuntimeException{方法:" + pjp.getSignature() + ", 參數:" + pjp.getArgs() + ",異常:" + messageCenterException.getException().getMessage() + "}", e); apiResponse = messageCenterException.getApiResponse(); } else if (e instanceof RuntimeException) { logger.error("RuntimeException{方法:" + pjp.getSignature() + ", 參數:" + pjp.getArgs() + ",異常:" + e.getMessage() + "}", e); apiResponse = new APIResponse(APIResponse.FAIL,null,e.getMessage()); } else { logger.error("異常{方法:" + pjp.getSignature() + ", 參數:" + pjp.getArgs() + ",異常:" + e.getMessage() + "}", e); apiResponse = new APIResponse(APIResponse.FAIL,null,e.getMessage()); } return apiResponse; } }