Can I send a custom Error message from server to client GRPC?

后端 未结 2 972
情书的邮戳
情书的邮戳 2021-01-03 23:32

I have created a simple GRPC server and client .

What i want to do is to create a custom error in the server and pass it to the client. My code looks as follows:<

2条回答
  •  时光说笑
    2021-01-03 23:53

    1.Yes 2.Maybe

    Avoid sending special objects (like new Error) over the wire. Send simple object with an error property and look for its value on the other end. See http://json.org/ to have an overview of easy transferable data.

    inside Server.js try

    function sayHello(call, callback) {
    
        try {
            var myCustomError = {};
            myCustomError.newStatus = 401;
            myCustomError.newMessage = 'custom unAuthorized error';
            console.log(Object.getOwnPropertyNames(myCustomError ));
            console.log(myCustomError);
            callback(null, {error: myCustomError, message: ""});
    
        } catch(e) {
            callback(e);
        }
    }
    

    inside the Client.js

    client.sayHello({name: user}, function(err, response) {
        var myCustomError= response.error;
        if (myCustomError) {
            console.log(Object.getOwnPropertyNames(myCustomError));
            console.log(myCustomError);
        }
    });
    

提交回复
热议问题