<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace plugin\admin\app\exception;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * Class Handler
 * @package support\exception
 */
class Handler extends \support\exception\Handler
{
    public function render(Request $request, Throwable $exception): Response
    {
        $debug = Config("app.debug"); 
        $data = [
            'msg' =>    \nl2br((string)$exception->getMessage()),
            'code' =>    $exception->getCode(),
            'line' =>    $exception->getLine(),
            'previous' =>    $exception->getPrevious(),
            'trace' =>    $exception->getTrace(),
            'trace_str' =>    $exception->getTraceAsString(),
            'file' =>    $exception->getFile(),
            'exception' =>    $exception,
            'method' =>    $request->method(),
            'url' =>    $request->path(),
            'post' =>    $request->post(),
            'get' =>    $request->get(),
            'header' =>    $request->header()
        ];
        if(method_exists($exception,'getData')){
            $data['data'] = $exception->getData();
        }
        if ($request->expectsJson()) {
            $json = [
                'code'  =>  $data['code'] ?: 500, 
                'msg'   =>  $debug ? $data['msg'] : 'Server internal error1', 
                'type'  =>  'failed',
                'data'  =>  $data
            ];
            $debug && $json['traces'] = (string)$exception;
            return new Response(200, ['Content-Type' => 'application/json'],
                \json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        $error = $debug ? \nl2br((string)$exception) : 'Server internal error2';
        return view('common/error',$data);
        //return new Response(500, [], $error);
    }
}
