thinkphp5自定义异常处理类 异常接管

配置文件里设置异常处理类:

   // 异常处理handle类 留空使用 \think\exception\Handle
    'exception_handle'       => '\think\exception\ExceptionHandler', 

ExceptionHandler.php文件如下:

<?php
namespace think\exception;

use think\Exception;
use think\config;
use think\exception\Handle;
/**
 * 自定义异常类 jee
 */
class ExceptionHandler extends Handle {
    /**
     * http状态码
     * @var unknown
     */
    public $httpCode = 500;

    public function render(\Exception $e){
        $debug_status = config("app_debug");
        if($debug_status){
            return parent::render($e);
        }else{
            return $this->show(2, $e->getMessage(), [], $this->httpCode);
        }

    }

    /**
     * 通用化API接口数据输出
     * @param int $status  操作成功还是失败: 1 成功 2 失败
     * @param int $errorcode 业务错误状态码
     * @param string $msg 信息提示
     * @param [] $result 数据
     * @param int $httpCode http状态码
     */
    public function show($status, $message ,$data = [] ,$httpCode = 200)
    {
        $data =  [
//            'status' => $status,
            'code'=>'500',
            'msg' => $message,
            'data' =>$data
        ];

        return json($data, $httpCode);

    }
}

我的微信:

ThinkPHP 6 (TP6) 中,自定义异常处理是一个重要的实践,它允许开发者创建自己的错误和异常处理器,以便更好地控制程序流程和提供更友好的错误信息。以下是TP6中自定义异常处理的基本步骤: 1. **创建异常**:首先,你需要创建一个继承自`Illuminate\Foundation\Exceptions\Handler`的,例如`App\Exceptions\CustomExceptionHandler`。在这个中,你可以定义具体的异常处理逻辑。 ```php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; class CustomExceptionHandler extends ExceptionHandler { // ... 自定义处理方法 ... public function render($request, Throwable $exception) { return parent::render($request, $exception); } // 添加其他处理方法,如记录日志、返回特定错误页面等 } ``` 2. **注册异常处理**:在`app/Http/Kernel.php`文件中,你需要将你的自定义异常处理器注册到`$container->resolve('Illuminate\Contracts\Http\Kernel')->setException_handler()`函数里。 ```php protected $exception_handlers = [ // 其他已存在的异常处理器... \App\Exceptions\CustomExceptionHandler::class, ]; ``` 3. **异常响应**:在`render`方法中,你可以定制异常的响应格式,比如使用JSON格式返回错误信息,或者渲染特定的视图。 ```php public function render($request, Throwable $exception) { if ($exception instanceof CustomException) { // 对于自定义异常,可以有专门的处理逻辑 return response()->json([ 'message' => $exception->getMessage(), 'code' => $exception->getCode(), ], $exception->getStatusCode()); } // 使用默认的异常处理逻辑 return parent::render($request, $exception); } // ... 其他自定义处理逻辑... ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值