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

核心实现 错误继承 instanceof

在做API时,需要对一些异常进行全局处理
比如添加用户执行失败时,需要返回错误信息

期望:

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

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

实现:

1.添加异常处理类

2.修改laravel异常处理

 

1.添加异常处理类

 

<?php
namespace App\Exceptions;
//./app/Exceptions/ApiException.php
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);
}

 

posted on 2018-09-06 16:39  小乔流水人家  阅读(654)  评论(0)    收藏  举报

导航