<?php

namespace App\Exceptions;

use App\Exceptions\Api\ApiException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use App\Facades\Servers\Logs\Log;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * 不报告的异常类型的列表
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {})->stop();
    }


    /**
     * 将异常呈现到HTTP响应中
     * 
     * 
     * @return \Illuminate\Http\JsonResponse
     */
    public function render($request, Throwable $e){
        // 如果是异常类型,获取异常的消息
        $msg            = $e->getMessage();
        // 错误信息
        $msg            = $msg ? $msg : '404';
        // 错误数据
        $data           = '';
        // 错误码
        $code           = 'sys_error';
        // http状态码
        $status         = 200;
        // 日志信息
        $message        = request()->ip().' ' .request()->method().' '. request()->getPathInfo().' '.$msg .' of file '.$e->getFile().' on line '.$e->getLine();
        // 如果是接口异常
        if( $e instanceof ApiException ){
            // 错误码
            $code       = $e->getErrCode();
            // 错误数据
            $data       = $e->getErrData();
        }else{
            // 拼接报错文件位置
            $message    .= ' of file '.$e->getFile().' on line '.$e->getLine();
        }
        // 要返回的数据
        $data           = ['code'=>($code == 'sys_error' ? 'error' : $code),'msg'=>$msg,'data'=>$data];
        // 记录日志
        Log::info($code,$message,['param'=>request()->all(),'return'=>$data,'user_agent'=>request()->header('user-agent')],['filename'=>str_ireplace('/','_',trim(request()->getPathInfo(),'/'))]);
        // 返回结果
        return          response()->json($data,$status,[],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

}
