Return JSON 对于 octoberCMS 的例外情况

Return JSON for exception with octoberCMS

我有一些自定义路线

Route::get('/files/', [
            'as' => 'read',
            'uses' => 'Myname\MyPlugin\Http\Controllers\FilesController@read'
        ]);

在我的某处 class 我有一个验证路径的函数

private function getPath()
{
    $path = Input::get('path');

    if (!$path)
    {
    throw new MyException('parameter is missing. path required', 400);
    }

    return base_path().'/'.$path;
}

我已经使用 JSOM 设置了自定义错误处理程序,但它是 OctoberCMS 的错误处理程序以 HTML 格式呈现错误。

您知道用自定义错误处理程序替换 OctoberCMS 的默认错误处理程序的方法吗? 谢谢

刚刚在文档中找到答案:https://octobercms.com/docs/services/error-log#exception-handling

10 月提供 App:error 来管理插件中的异常。

App::error(function(MyException $exception) {
//do what you want here
}

不要伪造为您的插件创建自定义异常。如果您使用通用 Exception,您将捕获所有异常。

由于这个问题在 Google.

上的可见性,我在这里发布了自定义错误处理程序的替代解决方案

由于 Github 上的这个问题,我在使用 App:error 时遇到问题:https://github.com/octobercms/october/issues/3416


与其使用 10 月的 App::error 进行自定义错误处理,不如尝试以下操作:

  1. 创建一个继承自 October 错误处理程序的自定义错误处理程序。例如,在 plugins/{AUTHOR}/{PLUGIN}/classes/CustomHandler.php 中创建以下 class (假设您正在为 OctoberCMS 开发插件)。覆盖处理程序的 render 方法。

    <?php
    
    namespace {AUTHOR}\{PLUGIN}\Classes; //<-- CHANGE ME OBVIOUSLY FOR YOUR PLUGIN
    
    use October\Rain\Foundation\Exception\Handler;
    use Illuminate\Support\Facades\Event;
    use Illuminate\Support\Facades\Response;
    use Exception;
    use Illuminate\Database\Eloquent\ModelNotFoundException; // As an example exception you want to handle ...
    
    /* Custom error handler which replaces the default error handler for OctoberCMS. */
    class CustomHandler extends Handler
    {
        /**
        * Render an exception into an HTTP response.
        *
        * @param  \Illuminate\Http\Request  $request
        * @param  \Exception  $exception
        * @return \Illuminate\Http\Response
        */
        public function render($request, Exception $exception)
        {
            /* Custom JSON response for ModelNotFoundException exceptions. */
            if($exception instanceof ModelNotFoundException){
                return Response::json(['error' => 'A record was not found for the resource that was requested.'], 404);
            }
    
            /* The rest of this code is just the 'default' code from OctoberCMS' error handler. */
            /* The only change is the code above this comment where I handle a specific exception in a unique way.*/
            /* i.e. I decided to return JSON for the error rather than an HTML error page (in debug mode). */
            if (!class_exists('Event')) {
                return parent::render($request, $exception);
            }
    
            $statusCode = $this->getStatusCode($exception);
            $response = $this->callCustomHandlers($exception);
    
            if (!is_null($response)) {
                return Response::make($response, $statusCode);
            }
    
            if ($event = Event::fire('exception.beforeRender', [$exception, $statusCode, $request], true)) {
                return Response::make($event, $statusCode);
            }
    
            return parent::render($request, $exception);
        }
    }
    
    1. 然后,在你的插件注册文件Plugin.php中,添加一个boot方法,代码如下:

    
    <?php namespace {AUTHOR}\{PLUGIN};
    
    use System\Classes\PluginBase;
    use {AUTHOR}\{PLUGIN}\Classes\CustomHandler; //<-- IMPORTANT
    use Illuminate\Contracts\Debug\ExceptionHandler;  //<-- IMPORTANT
    
    class Plugin extends PluginBase
    {
       /**
       * @var array Plugin dependencies
       */
       public $require = [];
    
    
       public function registerComponents()
       {
       }
    
       public function registerSettings()
       {
       }
    
       public function boot(){
    
    
           /* Replace the default error handler of OctoberCMS to return JSON format responses instead. */
           /* Also, this is used in order to control the responses for certain types of errors/exceptions. */
           /* We are going about it this way because App::error (as mentioned in the documentation for OctoberCMS), */
           /* was not returning the response properly presumably because of a bug. Argh... */
           $this->app->bind(
               ExceptionHandler::class,
               CustomHandler::class
           );
    
    
       }
    
    
    }
    
    

因为新的 CustomHandler.php 被添加到 classes 目录,新的 class 应该已经被拾取了。无需 composer dump-autoload -o 或更改 composer.json.

就是这样。当 ModelNotFoundException 发生时,给 Web 浏览器的响应将是您编写的 JSON(来自我们创建的自定义错误处理程序)。

相关链接: