从类构造函数之外的泛型类型创建新实例

时间:2020-02-19 08:38:16

标签: typescript generics

我想创建一个通用类,将我自己的自定义异常映射到预制的框架HTTP异常。所以我到目前为止有什么

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category');
            $table->string('title')->nullable();
            $table->string('img')->nullable();
            $table->timestamps();
        });

        Schema::create('stories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('story');
            $table->date('published_on');
            $table->integer('count_views')->default(0);
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger("category_id");
            $table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
        Schema::dropIfExists('stories');
    }
}

此抽象类从接口实现export abstract class MyCustomFilter< MyCustomException extends Error, TheirHttpException extends HttpException > implements Filter<MyCustomException> { public catch(exception: MyCustomException): void { // create a new instance of TheirHttpException // or access its non static fields and methods // ... main logic ... } } 函数。框架通过catch装饰器自动调用此catch函数。我想将我的异常映射到他们的http异常,因为我需要从Catch()函数中的两个异常中访问某些字段和方法。实施新的过滤器时,我要做的就是

catch

所以我在这里找到了功能的可能解决方案

https://stackoverflow.com/a/26696476/9945420

但是我不想将@Catch(KeyNotFoundException) // This will trigger the catch function export class MyFilterImplementation extends MyCustomFilter<KeyNotFoundException, NotFoundException> {} 传递给HttpException的构造函数,因为此异常需要在运行时基于{{1的MyCustomFilter参数创建}}功能。

我当前的解决方案:

我目前使用一种变通办法,方法是使用必填字段创建第二个函数。 exception函数调用第二个函数并传递所需的参数。

catch

但是我认为可以通过首先提到的方法来改善这一点...有什么想法吗?

0 个答案:

没有答案