JS调用C++函数抛出异常及捕捉异常详解

 更新时间:2021年08月19日 11:36:42   作者:永远的魔术1号  
这篇文章主要介绍了js调用C++函数的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

本文讲述如何利用v8::TryCatch捕捉js代码中发生的异常。

首先,声明TryCatch对象。

v8::TryCatch trycatch( isolate );

然后,定义抛出异常的函数:

void ThrowException( const v8::FunctionCallbackInfo<v8::Value>& info ) {
    v8::Isolate* isolate = info.GetIsolate();
    v8::HandleScope scope( isolate );

    v8::Local<v8::Value> exc = v8::Local<v8::Value>::New( info.GetIsolate(),
        v8::Exception::Error( v8::String::NewFromUtf8( isolate, "throw an exception" ).ToLocalChecked() ) );
    info.GetIsolate()->ThrowException( exc );
}

设置访问器访问C++函数:

v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New( isolate );
global->Set( isolate, "throwException",
    v8::FunctionTemplate::New( isolate, ThrowException ) );

因为异常发生在执行js文件期间,所以需要在Run函数后判断是否有异常发生。这里Run的结果没有继续调用ToLocalChecked(),因为result为NULL。

// Run the script to get the result.
v8::MaybeLocal<v8::Value> result = script->Run( context );
if ( trycatch.HasCaught() ) {
    v8::Local<v8::Message> message = trycatch.Message();
    ResolveMessage( message );
    return -1;
}

这样就可以在js文件中使用C++函数抛出异常,并解析异常信息。

main.cpp

// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "include/libplatform/libplatform.h"
#include "include/v8.h"

#include "point.h"

using namespace std;
using namespace v8;

const std::string fileName = "file.js";

// Reads a file into a v8 string.
MaybeLocal<String> ReadFile( Isolate* isolate, const string& name ) {
    FILE* file = fopen( name.c_str(), "rb" );
    if ( file == NULL ) return MaybeLocal<String>();

    fseek( file, 0, SEEK_END );
    size_t size = ftell( file );
    rewind( file );

    std::unique_ptr<char> chars( new char[size + 1] );
    chars.get()[size] = '\0';
    for ( size_t i = 0; i < size;) {
        i += fread( &chars.get()[i], 1, size - i, file );
        if ( ferror( file ) ) {
            fclose( file );
            return MaybeLocal<String>();
        }
    }
    fclose( file );
    MaybeLocal<String> result = String::NewFromUtf8(
        isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size) );
    return result;
}

void ThrowException( const v8::FunctionCallbackInfo<v8::Value>& info ) {
    v8::Isolate* isolate = info.GetIsolate();
    v8::HandleScope scope( isolate );

    v8::Local<v8::Value> exc = v8::Local<v8::Value>::New( info.GetIsolate(),
        v8::Exception::Error( v8::String::NewFromUtf8( isolate, "throw an exception" ).ToLocalChecked() ) );
    info.GetIsolate()->ThrowException( exc );
}

void ResolveMessage( v8::Local<v8::Message> message ) {
    v8::Isolate* isolate = message->GetIsolate();
    v8::Local<v8::Context> context = isolate->GetCurrentContext();

    int lineNum = message->GetLineNumber( context ).ToChecked();
    v8::String::Utf8Value err_msg( isolate, message->Get() );
    v8::String::Utf8Value err_src( isolate, message->GetSourceLine( context ).ToLocalChecked() );

    printf( "line %d, [error] %s, [error source] %s", lineNum, *err_msg, *err_src );
}

int main( int argc, char* argv[] ) {
    // Initialize V8.
    v8::V8::InitializeICUDefaultLocation( argv[0] );
    v8::V8::InitializeExternalStartupData( argv[0] );
    std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
    v8::V8::InitializePlatform( platform.get() );
    v8::V8::Initialize();

    // Create a new Isolate and make it the current one.
    v8::Isolate::CreateParams create_params;
    create_params.array_buffer_allocator =
        v8::ArrayBuffer::Allocator::NewDefaultAllocator();
    v8::Isolate* isolate = v8::Isolate::New( create_params );
    {
        v8::Isolate::Scope isolate_scope( isolate );

        // Create a stack-allocated handle scope.
        v8::HandleScope handle_scope( isolate );

        v8::TryCatch trycatch( isolate );

        v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New( isolate );
        global->Set( isolate, "throwException",
            v8::FunctionTemplate::New( isolate, ThrowException ) );

        // Create a new context.
        v8::Local<v8::Context> context = v8::Context::New( isolate, nullptr, global );

        // Enter the context for compiling and running the hello world script.
        v8::Context::Scope context_scope( context );

        {
            // Create a string containing the JavaScript source code.
            v8::Local<v8::String> source;
            if ( !ReadFile( isolate, fileName ).ToLocal( &source ) ) {
                fprintf( stderr, "Error reading '%s'.\n", fileName.c_str() );
                return -1;
            }

            // Compile the source code.
            v8::Local<v8::Script> script =
                v8::Script::Compile( context, source ).ToLocalChecked();

            // Run the script to get the result.
            v8::MaybeLocal<v8::Value> result = script->Run( context );
            if ( trycatch.HasCaught() ) {
                v8::Local<v8::Message> message = trycatch.Message();
                ResolveMessage( message );
                return -1;
            }
        }
    }

    // Dispose the isolate and tear down V8.
    isolate->Dispose();
    v8::V8::Dispose();
    v8::V8::ShutdownPlatform();
    delete create_params.array_buffer_allocator;
    return 0;
}

file.js

throwException();

运行结果:

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

相关文章

  • dword ptr指令详细解析

    dword ptr指令详细解析

    8086CPU的指令,可以处理两种尺寸的数据,byte和word。所以在机器指令中要指明,指令进行的是字操作还是字节操作
    2013-09-09
  • C++中单调栈的基本性质介绍

    C++中单调栈的基本性质介绍

    这篇文章主要介绍了单调栈的基本性质介绍,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-07-07
  • C/C++实操True and false详解

    C/C++实操True and false详解

    这篇文章主要给大家介绍了关于Python中常用的数据类型bool(布尔)类型的两个值:True和False的相关资料,通过示例代码给大家进行了解惑,让对这两个值有所疑惑的朋友们能有起到一定的帮助,需要的朋友下面来一起看看吧。
    2021-09-09
  • 深入解析C++编程中基类与基类的继承的相关知识

    深入解析C++编程中基类与基类的继承的相关知识

    这篇文章主要介绍了C++编程中基类与基类的继承的相关知识,包括多个基类继承与虚拟基类等重要知识,需要的朋友可以参考下
    2016-01-01
  • c语言main函数使用及其参数介绍

    c语言main函数使用及其参数介绍

    这篇文章主要介绍了c语言main函数使用及其参数介绍,需要的朋友可以参考下
    2014-04-04
  • C++实现将s16le的音频流转换为float类型

    C++实现将s16le的音频流转换为float类型

    这篇文章主要为大家详细介绍了如何利用C++实现将s16le的音频流转换为float类型,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下
    2023-04-04
  • C++ Virtual关键字的具体使用

    C++ Virtual关键字的具体使用

    这篇文章主要介绍了C++ Virtual关键字的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • C++多重继承引发的重复调用问题与解决方法

    C++多重继承引发的重复调用问题与解决方法

    这篇文章主要介绍了C++多重继承引发的重复调用问题与解决方法,结合具体实例形式分析了C++多重调用中的重复调用问题及相应的解决方法,需要的朋友可以参考下
    2018-05-05
  • C语言结构体嵌套与对齐超详细讲解

    C语言结构体嵌套与对齐超详细讲解

    这篇文章主要介绍了C语言结构体嵌套与对齐,C语言中结构体是一种构造类型,和数组、基本数据类型一样,可以定义指向该种类型的指针。结构体指针的定义类似其他基本数据类型的定义
    2022-12-12
  • C++实现简单遗传算法

    C++实现简单遗传算法

    这篇文章主要介绍了C++实现简单遗传算法,以实例形式较为详细的分析了遗传算法的C++实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-05-05

最新评论