美文网首页
简单ajax请求异常处理应用

简单ajax请求异常处理应用

作者: 一句话儿 | 来源:发表于2019-04-05 11:13 被阅读0次

<?php

  $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();

  }

成功处理不抛异常

<?php

  $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请求异常处理应用

      本文链接:https://www.haomeiwen.com/subject/kruhiqtx.html