Exemple #1
0
  public static void handleException(RestRequest request, RestResponse response, Throwable ex) {

    Throwable rootCause = ExceptionUtils.getRootCause(ex);
    rootCause = rootCause == null ? ex : rootCause;

    logger.error("捕获到Rest异常:request={}", request, rootCause);
    RestError restError = new RestError();
    restError.setErrorCode(2);

    if (ex instanceof RestServiceException) {

      RestServiceException rse = (RestServiceException) ex;

      if (rse.getErrorCode() != 0) {

        restError.setErrorCode(rse.getErrorCode());
      }

      restError.setErrorInfo(rse.getMessage());

    } else {

      restError.setErrorInfo(RestApiConstants.DEFAULT_ERROR_INFO);

      if (request.isDebug()) {

        String stackTrace = ExceptionUtils.getStackTrace(rootCause);
        // 截取有用的部分
        stackTrace = StringUtils.substringBefore(stackTrace, RestApiConstants.STACK_TRACE_BEFORE);
        response.setDebugInfo(stackTrace);
      }

      // 统计响应结果
      recordToErrorCounter(request.getCmd());
    }

    response.setStatusCode(500);
    response.setError(restError);
    response.setResponseTime(new Date());
  }