Laravel接口 接管“自定义异常类”教程

1、去 app\exceptions 目录下,新建 Apiexception.php;

<?php 
namespace App\Exceptions; 
 
/***
 * API 自定义异常类
 */
use Exception;

class ApiException extends Exception 
{ 
  
    //自定义异常处理
    public function SetErrorMessage($errorMsg='', $errorCode = '500'){
        $this->errorMsg = $errorMsg;
        $this->errorCode = $errorCode;
        return $this;  

    }

} 

 

2、修改 app\exceptions\handler.php 文件;

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception) 
    { 
        // 如果config配置debug为true ==>debug模式的话让laravel自行处理 
        $debug_status = config('app.debug'); // .env文件配置
        if($debug_status){ 
            return parent::render($request, $exception); 
        } 
        return $this->handle($request, $exception); 
    } 

     /**
      * 异常接管
      * 
      */
     public function handle($request, Exception $exception){ 
        //如果是接口请求,则抛出json
        if($request->is('api/*')) { 
             // 只处理自定义的APIException异常 
            if($exception  instanceof   \APP\Exceptions\ApiException ) {  //此处写ApiException文件所处路径
                $result = [ 
                    "status" => 2 , //操作状态: 1 成功 2 失败
                    "errorCode"=>$exception->errorCode,
                    "msg"    => $exception->errorMsg, 
                    "result"   => '', 
                ]; 
                return response()->json($result);
            } 

            //此处可以写多个自定义异常类
            if($exception  instanceof   \APP\Exceptions\otherException ) { 
                $result = [ 
                    "status" => 2 , //操作状态: 1 成功 2 失败
                    "errorCode"=>$exception->errorCode,
                    "msg"    => $exception->errorMsg, 
                    "result"   => '', 
                ]; 
                return response()->json($result);
            } 

            # 继续写其他自定义异常
            /***
             * code  
             * 
             * ***/
        } 
        return parent::render($request, $exception); 
    } 

 

3、使用

<?php

namespace App\Http\Controllers\Test;
use Illuminate\Routing\Controller;
use App\Exceptions\ApiException;

class IndexController extends Controller
{
    public function index(){
        throw (new ApiException)->SetErrorMessage("错了",'500');

    }

}

这就ok了!

 

整体思路:

使用时候,先实例化 自定义 异常,把错误信息传过去, 然后会回到 handler.php 里边显示。

 

注意事项:

1、测试时候,要注册一个路由再访问;

2、注意开启debug,在.env文件里边;

头像
  • ¥ 0.0元
  • 市场价:99.0元
  • ¥ 99.0元
  • 市场价:199.0元
  • ¥ 129.0元
  • ¥ 198.0元
  • 市场价:398.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: