<?php

namespace App\Exceptions;

use Illuminate\Session\TokenMismatchException;
use Psy\Exception\ErrorException;
use Illuminate\Database\QueryException;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use App\Services\UtilService;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

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

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Exception $exception)
    {
        $message =  '【'.date('Y-m-d H:i:s').'】生涯明信片项目:'.$exception->getMessage();
        $submitData = ['mobile_list'=>config('sign.DINGDING_PHONE'),'message'=>$message,'api_token'=>config('sign.DINGDING_TOKEN')];
        UtilService::postCurlJson(config('sign.DINGDING_URL'),$submitData,[]);
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Exception
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof TokenMismatchException) {
            $exception = new TokenMismatchException("网络异常，请稍后刷新重试");
        }

        if ($exception instanceof QueryException) {
            return response()->json(['error' => 5001, 'message' => '网络错误']);
        }

        if ($exception instanceof ErrorException) {
            return redirect(route('index'));
        }
        return parent::render($request, $exception);
    }
}
