简单ajax请求异常处理应用

  $flag = true;

  $data = array();

  try {

    if($flag == true){ //请求失败抛出异常

      throw new Exception("Processing Request success", 1);

    }else{ //请求成功也抛出异常

      throw new Exception("Processing Request fail", 2);

    }

  } catch (\Exception $th) { //统一处理异常,返回信息

    $message =  $th->getMessage();

    $code = $th->getCode();

    echo json_encode(['message' => $message, 'code' => $code, 'data' => $data]);

    die();

  }

成功处理不抛异常

  $flag = true;

  $data = array();

  try {

    if($flag == true){

      throw new Exception("Processing Request success", 1);

    }

    //以下为正常流程

  } catch (\Exception $th) {

    $message =  $th->getMessage();

    $code = $th->getCode();

    echo json_encode(['message' => $message, 'code' => $code, 'data' => $data]);

  }

  echo json_encode(['message' => '请求成功', 'code' => 10000, 'data' => $data]);

  die();

你可能感兴趣的:(简单ajax请求异常处理应用)