Laravel实践-自定义全局异常处理

在做API时,需要对一些异常进行全局处理

百牛信息技术bainiu.ltd整理发布于博客园
比如添加用户执行失败时,需要返回错误信息

// 添加用户
$result = User::add($user);
if(empty($result)){
    throw new ApiException('添加失败');
}

API 回复
{
    "msg" : "添加失败",
    "data" : "",
    "status" : 0 // 0为执行错误
}

那么我们就需要添加一个全局异常处理,专门用来返回错误信息

步骤

  • 添加异常处理类
  • 修改laravel异常处理
1.添加异常处理类
./app/Exceptions/ApiException.php
<?php
namespace AppExceptions;

class ApiException extends Exception
{
    function __construct($msg='')
    {
        parent::__construct($msg);
    }
}
2.修改laravel异常处理
./app/Exceptions/Handler.php

// Handler的render函数
public function render($request, Exception $e)
{
    // 如果config配置debug为true ==>debug模式的话让laravel自行处理
    if(config('app.debug')){
        return parent::render($request, $e);
    }
    return $this->handle($request, $e);
}

// 新添加的handle函数
public function handle($request, Exception $e){
    // 只处理自定义的APIException异常
    if($e instanceof ApiException) {
        $result = [
            "msg"    => "",
            "data"   => $e->getMessage(),
            "status" => 0
        ];
        return response()->json($result);
    }
    return parent::render($request, $e);
}

大功告成....

原文地址:https://www.cnblogs.com/bainiu/p/7560477.html